简体   繁体   中英

Select multiple elements from same column in mysql

I am currently trying to return something from my db and I don't get what I want. I have a query that returns me this :

[{username: 'tupac',
age: 20,
popularity: 35,
city: 'Paris',
country: 'France',
latitude: 48.8534,
longitude: 2.3488,
tag_id: 172 }]

But what if there are multiples entries in the tag_id column ? Can I return this ? They way I have it today returns me 3 objects if there are 3 tag_id. So if tupac has 3 or 4 tag_id linked to him can I have something like this ?

[{username: 'tupac',
age: 20,
popularity: 35,
city: 'Paris',
country: 'France',
latitude: 48.8534,
longitude: 2.3488,
tag_id: 172 
tag_id: 173
tag_id: 175} ]

This is my actual query :

SELECT usersinfo.username, usersinfo.age, 
usersinfo.popularity, userlocation.city, userlocation.country, 
userlocation.latitude, userlocation.longitude , user_tags.tag_id

FROM usersinfo, userlocation, user_tags
WHERE usersinfo.sex = "f" 
AND usersinfo.orientation = "s" 
AND usersinfo.username = userlocation.username 
AND usersinfo.username = user_tags.username
AND usersinfo.username != 'natedogg'

I've been reading some stuff and neither the operator 'IN' or 'GROUP_CONTACT' Can help me. Maybe I'm doing this wrong ?

Thanks for your help !

Try this:

SELECT 
    usersinfo.username, 
    usersinfo.age, 
    usersinfo.popularity, 
    userlocation.city, 
    userlocation.country, 
    userlocation.latitude, 
    userlocation.longitude , 
    (select group_concat(user_tags.tag_id)
     from user_tags
     where user_tags.username = usersinfo.username
     group by username) as tag_id
FROM usersinfo
    inner join userlocation on usersinfo.username = userlocation.username 
WHERE usersinfo.sex = "f" 
AND usersinfo.orientation = "s" 
AND usersinfo.username = user_tags.username
AND usersinfo.username != 'natedogg';

Notice I've change your where clause and I've added a join.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM