开发者

query sql and get result for foreign key's value(not id)

开发者 https://www.devze.com 2023-01-13 17:31 出处:网络
Table IMAGES: columns- imageID, Image, and categoryID*(this being the foreign key) Table CATEGORIES: columns categoryID, Category

Table IMAGES:

  • columns- imageID, Image, and categoryID*(this being the foreign key)

Table CATEGORIES:

  • columns categoryID, Category

and peform query for example:

 $sql = "SELECT categ开发者_运维知识库oryID FROM IMAGES WHERE image = 'exampleImage'";

I would get the result as an integer of the category ID i.e 1

My question is what would be the query to display the category that the ID belongs to? Or any suggestions on how to work around with multiple queries.


You want to use an inner join so it returns the records that match based on the join criteria.

SELECT Images.CategoryID, Category.Category
FROM IMAGES
INNER JOIN Category ON Category.CategoryID = Images.CategoryID
WHERE image = exampleimage


use a simple left join:

SELECT imageID, Image, IMAGE.categoryID, CATEGORIES.Category
FROM IMAGES
LEFT JOIN CATEGORIES
ON IMAGES.categoryID = CATEGORIES.categoryID
WHERE image = 'exampleImage'

use table aliases to make the statement shorter:

SELECT imageID, Image, i.categoryID, c.Category
FROM IMAGES i
LEFT JOIN CATEGORIES c
ON i.categoryID = c.categoryID
WHERE image = 'exampleImage'
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号