I'm trying to get column names from a table. I want to supply the row id and I want only the column names for which the value of that column for the specific row (identified by the id) is "true" (my table has a bunch of boolean fields).
I want something like:
SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME.value = true
AND TABLE_THE_COLUMN_IS_FROM.id = "some_id"
Where .value would be variable, basically checking each column to see if it were true.
I know I can just get the row's values and iterate through, returning only those with value true, but I wanted to see if there is a way to do it all in one step. Thanks in advance to anyone who knows!
There is no means in one query to dynamically scan through the table's schema and inspect its values. The best way to achieve what you want is the one you suggested: query for the row client-side and then cycle through the columns searching for the values you seek. The other alternative is to query for the table schema using the INFORMATION SCHEMA views client-side, build a SQL statement with a where clause that looks for a True value in all the boolean columns, execute that and inspect the results.
This is probably going to be rather ugly no matter how you cut it, but here's one option:
select columns.column_name
from bool_table
inner join information_schema.columns
on columns.table_schema = 'your_db'
and columns.table_name = 'bool_table'
and ((columns.column_name = 'bool_1' and bool_table.bool_1 = 1)
or (columns.column_name = 'bool_2' and bool_table.bool_2 = 1))
where bool_table.id = 25
You could also potentially query information_schema.columns to dynamically generate the list of column statements so that you could dynamically generate the query, and even execute it in a stored proc using dynamic sql in mysql.
Related
I am new to learning HIBERNATE and SQL.I want a query for count the number of columns available in the table. Please help me to do this task.
I tried the below query,but i am getting bulk manipulation exception.
Thank you.
Query colQuery = session.createSQLQuery("SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE table_schema =:'dn' AND table_name=:'tn'");
colQuery.setString("dn", "abc");
colQuery.setString("tn", "store_data");
int count=colQuery.executeUpdate();
I see several problems with your code. First, named parameters in your native query do not take single quotes around them, i.e. use :dn and not :'dn'. Next, you are trying to execute an update on a SELECT query. This is also wrong, because you are not updating any records, and you just need to call colQuery.list() to get back your result set. Finally, I believe you need to use Query#setParameter() to assign values to the parameters. Try using this code:
Query colQuery = session.createSQLQuery("SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE table_schema=:dn AND table_name=:tn");
colQuery.setParameter("dn", "abc");
colQuery.setParameter("tn", "store_data");
List<Object[]> rows = colQuery.list();
int rowCount = ((Integer) rows.get(0)[0]).intValue();
Note that I accessed the first row of the result set, and the first (and only) column in that first row to get the count.
Is there a way to retrieve the column names of a query that returns no data?
The result of this query would be empty.
Is there a way how to find the column names when there's no result?
Please note that I'm aware of solutions using DESCRIBE and select column_name from information_schema.columns where table_name='person';
but I need a more flexible solution that will fit these multicolumn queries.
Please also note that I am still using the original PHP MySQL extention (so no MySQLi, and no PDO).
If you wrap your query with the following SQL, it will always return the column names from your query, even if it is an empty query result:
select myQuery.*
from (select 1) as ignoreMe
left join (
select * from myTable where false -- insert your query here
) as myQuery on true
Note: When the results of the subquery are empty, a single row of null values will be returned. If there is data in the subquery it won't affect the output because it creates a cross-product with a single row...and value x 1 = value
Execute following command if the result of your previous query is empty
SHOW columns FROM your-table;
For more details check this.
I'm not sure if it will satisfy you but you can do this
SELECT *, COUNT(*) FROM table;
It will return null values (except last column which you can ignore) if the query is empty and you will be able to access all columns. It's not proper way of doing it and selecting names from INFORMATION_SCHEMA would be much better solution.
Please note that result is aggregated and you need to use GROUP BY to get more results if there are any.
You should ,
Select COLUMN_NAME From INFORMATION_SCHEMA.COLUMNS
Where TABLE_SCHEMA='yourdb'
AND TABLE_NAME='yourtablename';
Is there any way to do something like :
SELECT * FROM TABLE WHERE COLUMN_NUMBER = 1;
?
No, you can't. Column order doesn't really matter in MySQL. See the below question for more details.
mysql - selecting values from a table given column number
If your table has a column named COLUMN_NUMBER and you want to retrieve rows from the table where that column contains a value of '1', that query should do the trick.
I suspect that what you are trying to do is reference an expression in the select list with an alias. And that is not supported. An expression in the WHERE clause that references a column must reference the column by name.
We can play some tricks with inline views, to give an alias to an expression, but this is not efficient in terms of WHERE predicates, because of the way MySQL materializes a derived table. And, in that case, its a name given to the column in the inline view that has to be referenced in the outer query.
How I did it:
I'm trying to take (last 3 values of) column number 4 in sometable.
set #mydb=(SELECT DATABASE());
set #mycol=(select COLUMN_NAME from information_schema.columns where
table_schema=#mydb and table_name='sometable' and ordinal_position = 4);
SELECT Date,#mycol FROM sometable ORDER BY Date DESC LIMIT 3;
Of course, if Database name is known, first line could by whiped and #mydb replaced by real database name.
You can do this trick
Example:
$query="select * from employee";
$result=mysql_query($query);
$meta=mysql_fetch_field($result,0) // 0 is first field in table , 1 is second one ,,, etc
$theNameofFirstField=$meta->name; // this well return first field name in table
// now you can use it in other query
$seconQuery="select $theNameofFirstField from employee";
I would like to SELECT * FROM table where the first column is equal to a variable. It supposed that I don't know the column name.
I know I can do something like
SELECT * FROM table WHERE column_id = 1
But I can't compare the data.
How can I do that?
I found some solution with T-SQL but it doesn't interest me.
To be more accurate :
I'm developing an administration panel in my website where the "super" admin can directly modify the database. For that I can select a table and edit this table. But to do that, I'm using an only PHP script which showing all tables, we can select one and the script show all rows in the selected table. After that you select a row and you are redirected to a page where the problem is. This page can receive any table with only one row, so I want to SELECT the data contained in this row.
Images to understand:
The first one shows the tables.
The second shows the rows of a selected table.
The third shows (normally) the data of 1 row but in this picture we can see data of many rows.
selecto http://imageshack.us/g/135/selecto.png
I found a solution :
Try to explain:
First : I selected all form the specific table which was posted
$query="SELECT * FROM ".$_POST['table']."";
$result=mysql_query($query);
Second: I attributed to a variable the column name (which I didn't know)
while($fields=mysql_fetch_array($result))
{
$col = mysql_field_name($result,0);
$nb++;
}
Third: I selected data from the table where $col = id of the row
$sql = "SELECT * FROM ".$_POST['table']." WHERE ".$col."=".$_GET['idRow']."";
$result1=mysql_query($sql);
If you know how many columns there are, you could use this little trick here:
SELECT *
FROM (
SELECT null x1, null x2, ..., null xn
WHERE 1 = 0
UNION ALL
SELECT * FROM my_table
) t
WHERE t.x1 = something
In other databases than MySQL, renaming "unknown" columns would be even simpler, e.g. in PostgreSQL you could rename only the first column like this:
SELECT * FROM my_table t(x) WHERE x = something
If you don't know anything about the table
... you can quickly query the information_schema first:
SELECT column_name
FROM information_schema.columns
WHERE table_name = :my_table
AND ordinal_position = 1
A note on SQL injection
Please don't, DON'T do this. EVER:
$query="SELECT * FROM ".$_POST['table']."";
I've recently written an article about SQL injection. Every single vulnerability like yours will allow any script kiddie to dump your database, or worse.
The solution is to sanitize your input first. Ideally, you'll maintain a catalog of allowed table strings, compare your $_POST variable with those, and then concatenate the pre-defined table string into your SQL statement, NOT the user input.
I think you can use SHOW CREATE TABLE table_name to fetch the schema of the table. After that, you should already know every column.
In PHP you could do something like:
$col = 'users';
mysql_query("SELECT * FROM table WHERE $col = $something");
I am creating a utility which lets users enter a SQL query for the purposes of importing data to my database.
The first step is to show a list of resulting fields so the user can route them to the destination fields.
When users import from MSSQL, I can use SET FMTONLY ON to fetch the list of output columns that the query would produce if ran (assuming the query is valid in the first place).
I haven't been able to find a way to do this for MySQL. EXPLAIN doesn't list the resulting fields.
Given the following query:
SELECT CONCATENATE(first_name, " ", last_name) AS name, age, foo
FROM customers
ORDER BY name ASC;
I ultimately need to get a list of output fields only, like this:
{ "name", "age", "foo" }
How can I do this in MySQL?
SET FMTONLY ON still requires you to get the column names and types manually, it just generates an empty result set.
For MySQL, add a WHERE FALSE somewhere
SELECT CONCATENATE(first_name, " ", last_name) AS name, age, foo
FROM customers
WHERE FALSE
ORDER BY name ASC;
You get this lovely execution plan
"id";"select_type";"table";"type";"possible_keys";"key";"key_len";"ref";"rows";"Extra"
"1";"SIMPLE";NULL;NULL;NULL;NULL;NULL;NULL;NULL;"Impossible WHERE"
Then parse the columns as you would set fmtonly on with MSSQL
For complex queries (nested, group by, limit-ed), wrap it in a subquery
select * from (
<your wonderful brilliant complex query>
) x where false
MSSQL would have complained if the inner query contains ORDER BY without TOP, MySQL is ok with it.
I think you need to look at the resultsetmetada. I carries the number of columns, column name, and a few more about the result set.
I think you're looking for DESC {table_name}