联合两个查询,1返回ID列表,另一个显示其他数据

时间:2013-12-09 17:48:01

标签: mysql sql

我首先查询根据搜索字词返回ID列表:

SELECT GROUP_CONCAT(c.user_id) AS user_id_array
  FROM words_en AS w
  JOIN connections AS c
    ON w.id = c.word_id
 WHERE w.word = "love"

感谢我的查询返回用户的个人资料:

SELECT id, email, verified, level, name_surname, age, sex, profession, education, location, privacy, suspend FROM users LIMIT :start, :results

第二个查询需要在返回的第一个查询列表上执行IN()。我该怎么做?

我需要:

SELECT id, email, verified, level, name_surname, age, sex, profession, education, location, privacy, suspend FROM users LIMIT :start, :results IN(user_id_array)

我可以在两者之间使用php,但这并不好玩:)

我想出了这个:

SELECT u.id, u.email, u.verified, u.level, u.name_surname, u.age, u.sex, u.profession, u.education, u.location, u.privacy, u.suspend
  FROM words_en AS w
  JOIN connections AS c
    ON w.id = c.word_id
  JOIN users AS u
    ON u.id = c.user_id
 WHERE w.word = "love"

但这不是效率低下吗?我首先结合3张桌子而不是我选择......似乎不对。

1 个答案:

答案 0 :(得分:0)

过滤器(w.word =“love”)从'words_en'中得到1行 从带有过滤器的'connections'中选择word_id会给出许多独特的用户(因为连接是多对多链接,带有唯一的user_id + word_id对)
加入'用户'保存行数,因为'用户'的主键为user_id。

因此,您确切拥有与“love”关键字相关的用户数 完全等效的查询。