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

时间:2015-12-25 05:34:01

标签: mysql

我有下面的会员表

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

我想选择同时包含MemberID的{​​{1}}。

预期输出:

BOOKID 10 and 14

我尝试了以下代码,但它不起作用:

MemberID
1

3 个答案:

答案 0 :(得分:2)

您可以尝试这样:

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

这是SQLFIDDLE

另一种解决方案可以是这样使用JOIN

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

这是SQLFIDDLE

答案 1 :(得分:0)

您可以使用DISTINCT关键字

 select distinct MemberID from member where BookID

答案 2 :(得分:0)

您要做的是选择不同的MemberID。像

这样的东西
SELECT  DISTINCT MemberID FROM member
WHERE BookID IN (10,14)

假设您想要Id 10或12的图书的结果。