Choosing from multiple columns by column name stored in a column - mysql

I want to select from a table like this
|id|col_name|col1|col2|col3|col4|col5|...|col100|
| 1|col1 | 142| 241| 333| 417| 713|...| 125|
| 2|col5 | 927| 72| 403| 104| 136|...| 739|
| 3|col100 | 358| 842| 150| 125| 174|...| 103|
Select from column specified by col_name field. Something like
SELECT id,valueof(col_name) val FROM table1
which returns
|id|val|
| 1|142|
| 2|136|
| 3|103|

If you are using PHP (or modify the logic accordingly), you can do something like-
$colNames = array(col1, col5, col100); // or SELECT col_name FROM
table_name and store it in $colNames
foreach ($colNames as $val) {
$query = "SELECT $val FROM table_name WHERE col_name={$val}";
//execute this and store its result one-by-one into another array.
}
as I'm not sure if it could be done with single query.

Related

How to concat two rows into string from a result set in MySql?

Basicly this is my mysql query:
select distinct(shipment_tag) from ir_shipment_registry where shipment_id = '2020111'
and the result set:
| shipment_tag |
+--------------+
| Truck |
| Equipment |
| |
How can I concat the two result set into string so that i can assign it to a variable? I tried
SET #purchasetype = (select distinct(shipment_tag) from ir_shipment_registry where shipment_id = '2020111')
but it returns and error says: Subquery returns more than 1 row.
I want something in my variable like : #purchasetype = "Truck, Equipment".
Perhaps use GROUP_CONCAT here:
SET #purchasetype = (SELECT GROUP_CONCAT(shipment_tag SEPARATOR ', ') FROM ir_shipment_registry WHERE shipment_id = '2020111');

Using LIKE with prepared statement

I have a statement I wish to execute to find if a column containing a string contains a certain value.
+----+------+
| id | st |
+----+------+
| 0 | 2183 |
| 1 | 5820 |
| 2 | 2984 |
| ...| ... |
+----+------+
Say I wish to find all rows where st contains a 1, I would use these where conditions:
WHERE st LIKE "%1%"
OR st LIKE "1%"
OR st LIKE "1"
OR st LIKE "%1"
But how do I do this in a prepared statement?
$ps = $db->prepare("
SELECT id
FROM table
WHERE st LIKE "%:a%"
OR st LIKE ":a%"
OR st LIKE ":a"
OR st LIKE "%:a"
");
$ps->execute(array(
':a' => $var
));
This doesn't work evidently.
The % sign must be part of $var not part of the prepared Statement. also you only need %:a% it include all other parts of your where clause
$ps = $db->prepare("
SELECT id
FROM table
WHERE st LIKE :a
");
$ps->execute(array(
':a' => "%".$var."%"
));
ps = $db->prepare("
SELECT id
FROM table
WHERE st LIKE :a");
$ps->execute(array(
':a' => "%".$var."%"
));
Try above code.
And one more thing if you require rows which contains 1 in it,then there is no requirement of 4 like condition you only can achieve using '%1%'.
Hope this will help.

Substring reurns a number value instead of varchar

$query = mysql_query(SELECT * FROM test WHERE SUBSTRING(date,0,4)="1392") //for example 1392
echo query['name'];
i want to get 4 first character and check its equal with 1392 or not .
but its return 1054 my column name type is varchar and i have no idea about this.
MySQL count char from 1, not from 0 as php.
try
SUBSTRING(date,1,4)="1392"
or if you want the year
YEAR(date)="1392"
http://dev.mysql.com/doc/refman/5.5/en/string-functions.html#function_substring
EDIT test exemple
CREATE TABLE babak (name VARCHAR(20) NOT NULL, date VARCHAR(10) NOT NULL);
INSERT INTO babak SELECT 'test', '1391/11/11';
INSERT INTO babak SELECT 'correct', '1932/11/11';
SELECT * FROM babak WHERE YEAR(date) = 1932;
+---------+------------+
| name | date |
+---------+------------+
| correct | 1932/11/11 |
+---------+------------+
SELECT * FROM babak WHERE SUBSTRING(date, 1, 4) = 1932;
+---------+------------+
| name | date |
+---------+------------+
| correct | 1932/11/11 |
+---------+------------+
So your date is in varchar with the format yyyy/MM/dd, try this one:
SELECT *
FROM test
WHERE SUBSTRING(`date`,1,4) = '1932'
CLICK HERE FOR DEMO
mysql_query only returns a resource, you need to use that resource to fetch the result
$resource = mysql_query('SELECT * FROM test WHERE SUBSTRING(date,1,4)="1392"')
$result = mysql_fetch_assoc($resource);
echo $result['name'];

SQL query to remove certain text from each field in a specific column?

I recently recoded one of my sites, and the database structure is a little bit different.
I'm trying to convert the following:
*----*----------------------------*
| id | file_name |
*----*----------------------------*
| 1 | 1288044935741310953434.jpg |
*----*----------------------------*
| 2 | 1288044935741310352357.rar |
*----*----------------------------*
Into the following:
*----*----------------------------*
| id | file_name |
*----*----------------------------*
| 1 | 1288044935741310953434 |
*----*----------------------------*
| 2 | 1288044935741310352357 |
*----*----------------------------*
I know that I could do a foreach loop with PHP, and explode the file extension off the end, and update each row that way, but that seems like way too many queries for the task.
Is there any SQL query that I could run that would allow me to remove the file exentision from each field in the file_name column?
You can use the REPLACE() function in native MySQL to do a simple string replacement.
UPDATE tbl SET file_name = REPLACE(file_name, '.jpg', '');
UPDATE tbl SET file_name = REPLACE(file_name, '.rar', '');
This should work:
UPDATE MyTable
SET file_name = SUBSTRING(file_name,1, CHAR_LENGTH(file_name)-4)
This will strip off the final extension, if any, from file_name each time it is run. It is agnostic with respect to extension (so you can have ".foo" some day) and won't harm extensionless records.
UPDATE tbl
SET file_name = TRIM(TRAILING CONCAT('.', SUBSTRING_INDEX(file_name, '.', -1) FROM file_name);
You can use SUBSTRING_INDEX function
SUBSTRING_INDEX(str,delim,count)
Where str is the string, delim is the delimiter (from which you want a substring to the left or right of), and count specifies which delimiter (in the event there are multiple occurrences of the delimiter in the string)
Example:
UPDATE table SET file_name = SUBSTRING_INDEX(file_name , '.' , 1);

How to get the mysql table columns data type?

I want to get the column data type of a mysql table.
Thought I could use MYSQLFIELD structure but it was enumerated field types.
Then I tried with mysql_real_query()
The error which i am getting is query was empty
How do I get the column data type?
You can use the information_schema columns table:
SELECT DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'tbl_name' AND COLUMN_NAME = 'col_name';
The query below returns a list of information about each field, including the MySQL field type. Here is an example:
SHOW FIELDS FROM tablename
/* returns "Field", "Type", "Null", "Key", "Default", "Extras" */
See this manual page.
Most answers are duplicates, it might be useful to group them. Basically two simple options have been proposed.
First option
The first option has 4 different aliases, some of which are quite short :
EXPLAIN db_name.table_name;
DESCRIBE db_name.table_name;
SHOW FIELDS FROM db_name.table_name;
SHOW COLUMNS FROM db_name.table_name;
NB: In each case, you can also write FROM two times instead of db_name.table_name, example:
SHOW FIELDS FROM table_name FROM db_name
This gives something like :
+------------------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+------------------+--------------+------+-----+---------+-------+
| product_id | int(11) | NO | PRI | NULL | |
| name | varchar(255) | NO | MUL | NULL | |
| description | text | NO | | NULL | |
| meta_title | varchar(255) | NO | | NULL | |
+------------------+--------------+------+-----+---------+-------+
Second option
The second option is a bit longer :
SELECT
COLUMN_NAME, DATA_TYPE
FROM
INFORMATION_SCHEMA.COLUMNS
WHERE
TABLE_SCHEMA = 'db_name'
AND
TABLE_NAME = 'table_name';
It is also less talkative :
+------------------+-----------+
| column_name | DATA_TYPE |
+------------------+-----------+
| product_id | int |
| name | varchar |
| description | text |
| meta_title | varchar |
+------------------+-----------+
It has the advantage of allowing selection per column, though, using AND COLUMN_NAME = 'column_name' (or like).
To get data types of all columns:
describe table_name
or just a single column:
describe table_name column_name
Please use the below mysql query.
SELECT COLUMN_NAME, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH
FROM information_schema.columns
WHERE table_schema = '<DATABASE NAME>'
AND table_name = '<TABLE NAME>'
AND COLUMN_NAME = '<COLOMN NAME>'
First select the Database using use testDB; then execute
desc `testDB`.`images`;
-- or
SHOW FIELDS FROM images;
Output:
Refer this link
mysql> SHOW COLUMNS FROM mytable FROM mydb;
mysql> SHOW COLUMNS FROM mydb.mytable;
Hope this may help you
Query to find out all the datatype of columns being used in any database
SELECT distinct DATA_TYPE FROM INFORMATION_SCHEMA.columns
WHERE table_schema = '<db_name>' AND column_name like '%';
SHOW COLUMNS FROM mytable
Self contained complete examples are often useful.
<?php
// The server where your database is hosted localhost
// The name of your database mydatabase
// The user name of the database user databaseuser
// The password of the database user thesecretpassword
// Most web pages are in utf-8 so should be the database array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8")
try
{
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "databaseuser", "thesecretpassword", array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
}
catch(PDOException $e)
{
die('Could not connect: ' . $e->getMessage());
}
$sql = "SHOW COLUMNS FROM mytable";
$query = $pdo->prepare($sql);
$query->execute();
$err = $query->errorInfo();
$bug = $err[2];
if ($bug != "") { echo "<p>$bug</p>"; }
while ($row = $query->fetch(PDO::FETCH_ASSOC))
{
echo "<pre>" . print_r($row, true) . "</pre>";
}
/* OUTPUT SAMPLE
Array
(
[Field] => page_id
[Type] => char(40)
[Null] => NO
[Key] =>
[Default] =>
[Extra] =>
)
Array
(
[Field] => last_name
[Type] => char(50)
More ...
*/
?>
ResultSet rs = Sstatement.executeQuery("SELECT * FROM Table Name");
ResultSetMetaData rsMetaData = rs.getMetaData();
int numberOfColumns = rsMetaData.getColumnCount();
System.out.println("resultSet MetaData column Count=" + numberOfColumns);
for (int i = 1; i <= numberOfColumns; i++) {
System.out.println("column number " + i);
System.out.println(rsMetaData.getColumnTypeName(i));
}
SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA='SCHEMA_NAME' AND COLUMN_KEY='PRI';
WHERE COLUMN_KEY='PRI';
SELECT
TABLE_CATALOG,
TABLE_SCHEMA,
TABLE_NAME,
COLUMN_NAME,
DATA_TYPE
FROM INFORMATION_SCHEMA.COLUMNS