从mysql中的同一列中选择多个元素

时间:2017-01-30 14:50:46

标签: mysql

我目前正在尝试从我的数据库中返回一些东西,而我却得不到我想要的东西。 我有一个查询返回给我:

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

但是如果tag_id列中有多个条目怎么办?  我可以退货吗?如果有3个tag_id,我今天拥有它的方式会返回3个对象。 所以如果tupac有3或4个tag_id链接到他,我可以有这样的东西吗?

[{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} ]

这是我的实际查询:

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'

我一直在读一些东西,而不是操作员' IN'或者' GROUP_CONTACT'可以帮我。也许我做错了?

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

试试这个:

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';

请注意,我已更改您的where子句,并且我已添加了联接。