如何查找表(SQL)中的哪个列具有我们正在寻找的值? 例如我需要找到" CAR"在我的表中"汽车" .. 当我知道专栏名称时,我会写:
select * from Automobile where AutomobileName='CAR'
但是考虑到我不知道哪个列包含值,那么?
答案 0 :(得分:3)
这是任何数据库论坛中最常见的问题之一。让我向您展示Oracle数据库中的测试用例:
我想搜索具有价值' SCOTT'的模式中的所有表格。我会打印TABLE_NAME和COLUMN_NAME。
版本:
SQL> select banner from v$version;
BANNER
--------------------------------------------------------------------------------
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 - 64bit Production
PL/SQL Release 12.1.0.1.0 - Production
CORE 12.1.0.1.0 Production
TNS for 64-bit Windows: Version 12.1.0.1.0 - Production
NLSRTL Version 12.1.0.1.0 - Production
测试案例
SQL> set serveroutput on;
SQL> DECLARE
2 lcount NUMBER;
3 lquery VARCHAR2(200);
4 BEGIN
5 FOR data IN (SELECT *
6 FROM user_tab_columns) LOOP
7 lquery := 'select count(*) from '
8 ||data.table_name
9 ||' where '
10 ||data.column_name
11 ||' like ''%SCOTT%''';
12
13 EXECUTE IMMEDIATE lquery INTO lcount;
14
15 IF lcount > 0 THEN
16 dbms_output.Put_line(data.column_name
17 ||'-----'
18 ||data.table_name);
19 END IF;
20 END LOOP;
21 END;
22 /
ENAME-----EMP
PL/SQL procedure successfully completed.
SQL>
所以你输出为COLUMN_NAME - > ENAME和TABLE_NAME - >具有价值' SCOTT'。
的EMP根据会员要求澄清:
SQL> CREATE TABLE t AS
2 SELECT 'SCOTT' new_ename
3 FROM dual;
Table created.
SQL>
SQL> DECLARE
2 lcount NUMBER;
3 lquery VARCHAR2(200);
4 BEGIN
5 FOR data IN (SELECT *
6 FROM user_tab_columns) LOOP
7 lquery := 'select count(*) from '
8 ||data.table_name
9 ||' where '
10 ||data.column_name
11 ||' like ''%SCOTT%''';
12
13 EXECUTE IMMEDIATE lquery INTO lcount;
14
15 IF lcount > 0 THEN
16 dbms_output.Put_line(data.column_name
17 ||'-----'
18 ||data.table_name);
19 END IF;
20 END LOOP;
21 END;
22 /
NEW_ENAME-----T
ENAME-----EMP
PL/SQL procedure successfully completed.
SQL>
所以,现在您可以根据需要查看输出。
答案 1 :(得分:1)
如果你不知道它包含哪一列,你必须全部测试它们:
SELECT *
FROM Automobile
WHERE AutomobileName = 'CAR'
OR AutomobileMake = 'CAR'
OR AutomobileYear = 'CAR'
...
如果您需要知道找到了哪个列,可以使用UNION
这样:
SELECT 'Name' AS WhichColumn, *
FROM Automobile
WHERE AutomobileName = 'CAR'
UNION
SELECT 'Make' AS WhichColumn, *
FROM Automobile
WHERE AutomobileMake = 'CAR'
UNION
SELECT 'Year' AS WhichColumn, *
FROM Automobile
WHERE AutomobileYear = 'CAR'
...
答案 2 :(得分:0)
您需要使用全文搜索。语法取决于mysql中的db引擎,例如
SELECT productName, productline
FROM products
WHERE MATCH(productline,productline) AGAINST('Classic')
有关详细信息,请参阅http://www.mysqltutorial.org/introduction-to-mysql-full-text-search.aspx