SQL Join Ads with their Fields 将字段显示为列
Posted
技术标签:
【中文标题】SQL Join Ads with their Fields 将字段显示为列【英文标题】:SQL Join Ads with their Fields show fields as columns 【发布时间】:2017-08-06 07:23:04 【问题描述】:我有一个 Ads 表和一个 Ads_field 表,当我加入时,我会为一个广告获得多行,因为它们有多个字段
有没有办法将字段显示为列?
SELECT Ads.CITY_ID,Ads.PRICE,Ads.CREATED_DATE,Ads.HAS_IMAGES,
Ads.TITLE, Ads.DESCRIPTION, loc_cities.name as city, CATEGORY.NAME as
category_name, loc_countries.country_name as
country,Ads_fields.field_value
FROM Ads
INNER JOIN loc_cities ON Ads.CITY_ID=loc_cities.id
INNER JOIN CATEGORY ON Ads.CATEGORY_ID=CATEGORY.ID
INNER JOIN loc_countries ON Ads.country_code=loc_countries.ID
INNER JOIN Ads_fields ON Ads.ID=Ads_fields.ad_id
WHERE CONVERT(Ads.TITLE USING utf8) LIKE '%reqqa%'
or CONVERT(Ads.DESCRIPTION USING utf8) LIKE '%reqqa%'
or CONVERT(loc_cities.name USING utf8) LIKE '%reqqa%'
or CONVERT(loc_countries.country_name USING utf8) LIKE '%reqqa%'
or CONVERT(CATEGORY.name USING utf8) LIKE '%reqqa%'
LIMIT 50
【问题讨论】:
php 中的 while 循环将是最简单、最快且最具可扩展性的解决方案。 绝对正确但是我想使用单个查询实现关键字搜索,while 循环最适合获取和显示数据 【参考方案1】:一种简单的方法是将 field_value 显示为字符串逗号分隔
SELECT
Ads.CITY_ID,Ads.PRICE
, Ads.CREATED_DATE,Ads.HAS_IMAGES
, Ads.TITLE
, Ads.DESCRIPTION
, loc_cities.name as city
, CATEGORY.NAME as category_name
, loc_countries.country_name as country
, group_concat(Ads_fields.field_value)
FROM Ads
INNER JOIN loc_cities ON Ads.CITY_ID=loc_cities.id
INNER JOIN CATEGORY ON Ads.CATEGORY_ID=CATEGORY.ID
INNER JOIN loc_countries ON Ads.country_code=loc_countries.ID
INNER JOIN Ads_fields ON Ads.ID=Ads_fields.ad_id
WHERE CONVERT(Ads.TITLE USING utf8) LIKE '%reqqa%'
or CONVERT(Ads.DESCRIPTION USING utf8) LIKE '%reqqa%'
or CONVERT(loc_cities.name USING utf8) LIKE '%reqqa%'
or CONVERT(loc_countries.country_name USING utf8) LIKE '%reqqa%'
or CONVERT(CATEGORY.name USING utf8) LIKE '%reqqa%'
GROUP BY Ads.CITY_ID,Ads.PRICE
, Ads.CREATED_DATE,Ads.HAS_IMAGES
, Ads.TITLE
, Ads.DESCRIPTION
, loc_cities.name
, CATEGORY.NAME
, loc_countries.country_name
LIMIT 50
【讨论】:
, loc_cities.name as city , CATEGORY.NAME as category_name , loc_countries.country_name as country 不起作用必须删除最后三行中的别名 @AhmedSaleh 正确。答案已更新(错误的复制和粘贴)以上是关于SQL Join Ads with their Fields 将字段显示为列的主要内容,如果未能解决你的问题,请参考以下文章
SQL Server - INNER JOIN WITH DISTINCT
Oracle SQL UPDATE SELECT with JOIN 出错
PHP 报错:Deprecated: Methods with the same name as their class will not be constructor...
Hive指定位置增加字段及解决columns have types incompatible with the existing columns in their respective positio
ESPCMS做的网站,报错Deprecated: mysql_pconnect(): 或 Deprecated: Methods with the same name as their class