gpt4 book ai didi

mysql - 如何对 MySQL 表进行数据出现搜索

转载 作者:行者123 更新时间:2023-11-29 05:38:05 25 4
gpt4 key购买 nike

我是 MySQL 和 PHP 的新手。我有 2 个这样的表,行数超过数千。

Table "Company A" 
id | Date | Prize_1 | Prize_2 | Prize_3 | Prize_Consolation
1 | 2011-01-13 | "car" | "ipad2" | "bag" | "mouse"
2 | 2011-02-13 | "ps3" | "iphone4" | "mouse" | "bag"

Table "Company B"
id | Date | Prize_1 | Prize_2 | Prize_3 | Prize_Consolation
1 | 2011-01-18 | "tv" | "iphone4" | "ipod" | "bag"
2 | 2011-02-13 | "iphone4" | "ipad" | "bag" | "mouse"

用户将随机发送查询以搜索“奖品”的历史信息,时间和颁发公司。

示例:我想在两个表上查询奖品“iphone4”,它应该返回如下结果:

Company   | Date       | Prize
Company A | 2011-02-13 | Prize_2
Company B | 2011-01-18 | Prize_2
Company B | 2011-02-13 | Prize_1

Total 3 prizes for "iphone4"

什么 MySQL 查询可以实现此查找搜索?

最佳答案

这些确实不应该是两个单独的表,而应该是一个带有公司标识列的表。

然而,您的情况可以通过 hackish 方式解决:

SELECT
'Company A' AS Company,
Date,
CASE
WHEN Prize_1 = 'iphone4' THEN 'Prize_1'
WHEN Prize_2 = 'iphone4' THEN 'Prize_2'
WHEN Prize_3 = 'iphone4' THEN 'Prize_3'
WHEN Prize_Consolation = 'iphone4' THEN 'Prize_Consolation'
ELSE NULL
END AS Prize
FROM `Company A`
WHERE
Prize_1 = 'iphone4'
OR Prize_2 = 'iphone4'
OR Prize_3 = 'iphone4'
OR Prize_Consolation = 'iphone4'
/* UNION performs the same query against both tables and combine the results */
UNION
SELECT
'Company B' AS Company,
Date,
CASE
WHEN Prize_1 = 'iphone4' THEN 'Prize_1'
WHEN Prize_2 = 'iphone4' THEN 'Prize_2'
WHEN Prize_3 = 'iphone4' THEN 'Prize_3'
WHEN Prize_Consolation = 'iphone4' THEN 'Prize_Consolation'
ELSE NULL
END AS Prize

来自 公司 B在哪里Prize_1 = 'iphone4'或者 Prize_2 = 'iphone4'或者 Prize_3 = 'iphone4'或 Prize_Consolation = 'iphone4'

更适合此设计的表格布局如下所示:

Table Prizes
---------------
id INT AUTO_INCREMENT,
Date DATETIME,
Company VARCHAR(256),
Prize_Type INT,
Prize_Item VARCHAR(256)

Table Prize_Types
---------------
Prize_Type INT AUTO_INCREMENT PRIMARY KEY,
Prize_Description VARCHAR(32)

奖品

1 | 2012-01-28 08:00:00 | 'Company A' | 3 | 'some prize'
2 | 2012-01-28 08:00:00 | 'Company A' | 2 | 'ipad'
3 | 2012-01-28 08:00:00 | 'Company A' | 1 | 'junky phone'
4 | 2012-01-28 08:00:00 | 'Company b' | 4 | 'iphone4'

奖品类型

1 | 'Prize 1'
2 | 'Prize 2'
3 | 'Prize 3'
4 | 'Consolation Prize'

查询为:

SELECT
Company,
Date,
Prize_Item,
Prize_Description
FROM Prizes JOIN Prize_Types ON Prize_Types.Prize_Type = Prizes.Prize_Type
WHERE Prize_Item = 'iphone4'

事实上,您可能还希望将公司和奖品规范化到它们自己的表中,就像 Prize_Types 一样。

关于mysql - 如何对 MySQL 表进行数据出现搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9045221/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com