简体   繁体   English

查询以获取具有或不具有组concat的多行

[英]query to get multiple rows with or without group concat

I have the following table structure: 我具有以下表结构:

 users:
    id PK
    username
    email
    salt
    password
    date_created

questions:
    id PK
    user_id FK(users)
    title
    date_created
    date_updated

answers:
    id PK
    question_id FK(questions)
    user_id FK(users)
    body
    date_created

So I need a query that gets data from these tables and displays the user's last 5 questions and for each question the first 3 answers. 因此,我需要一个从这些表中获取数据并显示用户的最后5个问题以及每个问题的前3个答案的查询。 Something like this: 像这样:

"What is my favorite color? posted by user

red - posted by user1
green - posted by user2
yellow - posted by user3

.....
"

So this is the display I am aiming for. 这就是我想要的显示。 How can I do this in 1 query? 如何在1个查询中执行此操作? Should I use group concat to group the multiple answers for 1 question? 我应该使用群组连击将1个问题的多个答案分组吗? Or should I get the results and parse the array in PHP to group the answers by question_id. 还是我应该得到结果并用PHP解析数组以按问题ID将答案分组。 Also I need this query to be very fast. 另外,我需要此查询要非常快。 I am not sure if it will be faster making 1 query or making multiple queries that get the user questions and after that the question answers. 我不确定是否会更快地进行1个查询或进行多个查询以获取用户问题,然后问题得到解答。

I think the key "hint" I would give is that you can use regular CONCAT() inside of GROUP_CONCAT(); 我认为我要给出的关键“提示”是,您可以 GROUP_CONCAT() 内部使用常规的CONCAT(); and then use JOINs and perhaps some of the techniques mentioned in the comments to get you the intermediate result-set that those two functions need to get you your output. 然后使用JOIN和注释中提到的某些技术来获取中间结果集,这是两个函数获取输出所需要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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