简体   繁体   English

如何选择多行mysql表作为单行

[英]How to select multiple rows of mysql table as a single row

I have member table like below 我有如下的会员表

MemberID    Name     BookID
    1       ABC         10
    1       ABC         14
    2       XYZ         10
    3       PQR         14

I want to select a MemberID that contains both the BOOKID 10 and 14 in single row. 我想选择一个包含单行BOOKID 10 and 14MemberID

Expected Output: 预期产出:

MemberID
1

I have tried below code but it doesnt work: 我试过下面的代码,但它不起作用:

select MemberID from member where BookID IN (10,14)

You can try like this: 你可以尝试这样:

SELECT MemberID, GROUP_CONCAT(BookID) AS BookID
FROM member
GROUP BY MemberID
HAVING FIND_IN_SET(10, BookID) > 0 AND FIND_IN_SET(14, BookID) > 0

Here is the SQLFIDDLE . 这是SQLFIDDLE

Another solution can be using JOIN like this: 另一个解决方案是使用JOIN如下所示:

SELECT x.MemberID
FROM member x
INNER JOIN member y ON x.MemberID = y.MemberID
  AND x.BookID = 10
  AND y.BookID = 14

Here is the SQLFIDDLE . 这是SQLFIDDLE

您可以使用DISTINCT关键字

 select distinct MemberID from member where BookID

What you will want to do is select distinct MemberID. 您要做的是选择不同的MemberID。 Something like 就像是

SELECT  DISTINCT MemberID FROM member
WHERE BookID IN (10,14)

Assuming you want results for books with Id 10 or 12. 假设您想要Id 10或12的书籍的结果。

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

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