alexx0186
alexx0186

Reputation: 1557

How do use the nested INSERT/SELECT command in this case?

I have this command:

INSERT INTO table2 (username,profile) SELECT DISTINCT username,profile 
FROM table1 WHERE profile='$profile' and username <> '$sender'

My problem is I want this: INSERT INTO table2 (username,profile,type) where type is gonna be the same string, say "string"

Important: I only want username to be DISTINCT. profile and type can be the same. Also, profile will always be the same value.

How can I achieve that?

Thanks a lot, regards

Upvotes: 0

Views: 119

Answers (2)

Ian Atkin
Ian Atkin

Reputation: 6356

I'm making a huge assumption that you're looking for output something like...

UserFred profile1 type1
UserBill profile2 type1
UserJim  profile1 type8

You need to apply a GROUP BY statement in the subselect...

INSERT INTO table2 (username,profile)
   SELECT DISTINCT username,profile 
   FROM table1 WHERE profile='$profile' and username <> '$sender'
   GROUP BY username;

Upvotes: 1

eggyal
eggyal

Reputation: 125865

INSERT INTO table2 (username, profile, type)
SELECT username, profile, "string"
FROM table1
WHERE profile='$profile' AND username <> '$sender'
GROUP BY username

Please please please be absolutely certain that $profile and $sender have been cleaned of possible SQL injection attacks (if that means nothing to you, go read about Bobby Tables). You'd be far better off using prepared statements, into which you pass your variables as parameters that do not get evaluated for SQL.

Upvotes: 2

Related Questions