使用带有2个表的连接时,MySql选择限制1

时间:2014-09-10 12:51:27

标签: mysql sql

在与amgb进行联接时,我实际上是尝试使用限制从amga中选择一条记录。

我的表格是这样的:

阿姆加

"id"    "itemId"    "itemTempId"    "itemName"                  "itemCountry"   "userId"
"1"     "US1"       "T001"          "Samsung Galaxy Note 5"     "US"            "1"
"2"     "CA2"       "T002"          "Samsung Galaxy Note 6"     "CA"            "2"
"3"     "UK3"       "T003"          "Samsung Galaxy Note 7"     "UK"            "3"

amgb

"id"    "itemId"    "itemTempId"    "itemImageName"     "userId"
"1"     "US1"       "T001"          "front.jpg"         "1"
"2"     "US1"       "T001"          "side-left.jpg"     "1"
"3"     "US1"       "T001"          "side-right.jpg"    "1"
"4"     "US1"       "T001"          "back.jpg"          "1"
"5"     "CA2"       "T002"          "front.jpg"         "2"
"6"     "CA2"       "T002"          "side-left.jpg"     "2"
"7"     "CA2"       "T002"          "side-right.jpg"    "2"
"8"     "CA2"       "T002"          "back.jpg"          "2"
"9"     "UK3"       "T003"          "front.jpg"         "3"

用简单的语言,这相当于: select itemName from amga where itemId = 'US1' and userId = 1 along with 1 itemImageName from amgb where itemId = sameOneAsBefore and userId = sameOneAsBefore

我希望的最终结果就像这样简单: Samsung Galaxy Note 5 | front.jpg - 来自amga的itemName和来自amgb的itemImageName,其中userId = 1且itemId = US1

但我没有看到我出错的地方,尽管所有的连接和其他一切都是正确的。可能导致问题的原因/* SQL Error (1054): Unknown column 'b.userId' in 'on clause' */

SELECT  a.itemName, b.itemImageName 
FROM amga a 
LEFT JOIN (
    SELECT
        itemImageName
    FROM
        amgb
    LIMIT 1
) b
ON a.userId = b.userId and a.itemId = b.itemId  
WHERE a.userId = 1 and a.itemId = 'US1';

4 个答案:

答案 0 :(得分:1)

尝试使用它: -

SELECT  a.itemName, b.itemImageName 
FROM amga a 
LEFT JOIN (
           SELECT itemId, userId, itemImageName
           FROM amgb
           LIMIT 1
          ) b
ON a.userId = b.userId and a.itemId = b.itemId  
WHERE a.userId = 1 and a.itemId = 'US1';

答案 1 :(得分:1)

如果子查询返回一列且不超过一条记录,则可以将其作为查询中的列包含在其中:

SELECT  a.itemName,
  (SELECT itemImageName
    FROM amgb b
    WHERE a.userId = b.userId AND a.itemId = b.itemId
    LIMIT 1
  ) AS itemImageName
FROM amga a 
WHERE a.userId = 1 AND a.itemId = 'US1';

答案 2 :(得分:-1)

SELECT  a.itemName, b.itemImageName 
FROM amga a 
LEFT JOIN (
    SELECT
        itemImageName, userId
    FROM
        amgb
    LIMIT 1
) b
ON a.userId = b.userId and a.itemId = b.itemId  
WHERE a.userId = 1 and a.itemId = 'US1';

答案 3 :(得分:-1)

你能试试吗

SELECT  a.itemName, b.itemImageName 
FROM amga a 
LEFT JOIN (
    SELECT
        itemImageName
    FROM
        amgb b
    LIMIT 1
) <= 1
ON a.userId = b.userId and a.itemId = b.itemId  
WHERE a.userId = 1 and a.itemId = 'US1';