How get the columnames from select query in MySQL? - mysql

Is it possible to get the column names using a query in MySQL? For example, I have a SELECT query:
SELECT name AS 'name', surname AS 'col1', last_name AS 'col2' FROM tb_people;
So, I want to get "Only with one SQL query" like:
Columns or alias of my query
--------
name
col1
col2
I try something similar to:
SHOW COLUMNS (SELECT name AS 'name', surname AS 'col1', last_name AS 'col2' FROM tb_people)
And with
DESCRIBE (SELECT name AS 'name', surname AS 'col1', last_name AS 'col2' FROM tb_people)
But these return SQL errors.

Why don't you do this in your application? MySql API in most languages provide functions to fetch all sorts of field information including name from the results returned by MySql. For example in PHP you can use mysql_fetch_field() on the results returned by mysql_query() to fetch field information.
This is how it is done in PHP, there must be equivalent functions in the language you are using:
$res = mysql_query( "SELECT name AS 'name', surname AS 'col1', last_name AS 'col2' FROM tb_people" );
for( $i = 0; $i < mysql_num_fields( $res ); ++$i ) {
$fieldInfo = mysql_fetch_field( $res, $i );
echo $fieldInfo[ 'name' ].'<br />';
}
results:
name
col1
col2

Hey I have used this successfully in the past, but I don't know if it compatible with all versions:
SELECT name FROM syscolumns
WHERE id = (SELECT id FROM sysobjects
WHERE name= 'MyTableName')
ORDER by colorder
If you installed MySQL server 5, you may get around this problem easily:
use information_schema
SELECT * FROM information_schema.`COLUMNS` C limit 5
WHERE table_name = 'your_table_name'
Cheers!

Related

Doctrine oridinal number with mysql (Error: Expected Literal, got '#')

I need to have an oridinal number from mysql database. I found how emulate of row_num in mysql like this:
SET #row=0;
SELECT * FROM (
SELECT (#row:=#row+1) AS no, id, name FROM `attribute` ORDER BY id
) t WHERE name LIKE "%Jo%"
I begin code with:
$this->getEntityManager()->getConnection()->exec("SET #counter = 0");
and I tried:
$this->result = $this->createQueryBuilder('a')
->select('a')
->where($expr->in('att.ordinal_number', $this->createQueryBuilder('att')->
select('(#counter:=#counter+1) AS ordinal_number')->
from(\App\Entity\Attribute::class, 'att')->
orderBy('att.id')->getDQL()))
and I tried:
$this->result = $this->createQueryBuilder('a')
->select('a')
->addSelect('(SELECT (#counter:=#counter+1) AS oridinal_number, id, '
.' name FROM App:Entity:Atrribute ORDER BY id)')
Above give me:
Error: Expected Literal, got '#'
Anybody know how to emulate row_number in doctrine with mysql?
Thanks in advance.
AFAIK there is no direct way to incorporate these DB variables in DQL or query builder, you will need to execute Native SQL and then use ResultSetMapping class to map the result of query to your entity
SQL
SELECT *
FROM (
SELECT (#row:=#row+1) AS no,
id,
name
FROM `attribute` ,(SELECT #row:=0) t
ORDER BY id
) t WHERE name LIKE "%Jo%"
Resultset Mapping
$rsm = new ResultSetMapping;
$rsm->addEntityResult('Attribute', 'a');
$rsm->addFieldResult('a', 'id', 'id');
$rsm->addFieldResult('a', 'name', 'name');
$rsm->addScalarResult('no', 'no');
$query = $this->_em->createNativeQuery('SELECT *
FROM (
SELECT (#row:=#row+1) AS no,
id,
name
FROM attribute ,(SELECT #row:=0) t
ORDER BY id
) t WHERE name LIKE ?',$rsm);
$query->setParameter(1, '%Jo%');
$users = $query->getResult();

How to check if a variable equals to part of one of the columns in a table in the Database?

For example I have a variable $num = 123; and another one called `$name=joe;' , and there is a Database that contains a table called "data" and inside this table there are two columns (num [type=varchar(255)] - name[type=varchar(255)]) .
For example these query exists in the DB :
num = 123456 , name = joe
How to make a check that the first "3" numbers equals the $num variable and the name equals variable $name ?
I tried this but it didn't work:
SELECT * FROM data Where SUBSTRING(num , 0 , 3) = '123' AND name = 'joe'
In MySQL, substring indexing starts at 1:
WHERE SUBSTRING(num , 1 , 3) = '123' AND name = 'joe'
But LEFT() or LIKE would more commonly be used:
WHERE LEFT(num , 3) = '123' AND name = 'joe'
WHERE num = '123%' AND name = 'joe'
The advantage of LIKE is that it can make use of an index . . . even one on (name, num).
The MySQL substring() function is 1-based, not 0-based, so this should work for you:
SELECT * FROM data Where SUBSTRING(num , 1 , 3) = '123' AND name = 'joe'

mysql case sensitive query for fieldnames

I would like the query to select only if there is a column named firstName. If the column is firstname then the query should not return anything.
SELECT firstName as currentName from tableNew WHERE id = $Id
I tried the code below but does not work
SELECT binary firstName as currentName from tableNew WHERE id = $Id
Can you please help?
On Unix, table names are case sensitive. On Windows, they are not.
Column, index, and stored routine names are not case sensitive on any
platform, nor are column aliases.
If you have access to INFORMATION_SCHEMA do this:
SELECT firstName as currentName from tableNew WHERE id = $Id AND (SELECT COUNT(TABLE_NAME)
FROM information_schema.COLUMNS
WHERE
TABLE_SCHEMA = 'mydbname'
AND TABLE_NAME = 'tableNew'
AND BINARY COLUMN_NAME = 'firstName') > 0;

zend select from two tables 3 sets of rows

I have this problem using Zend and I think its db related at all:
I have two tables, one contains:
id, ..., file, desc, date
and the second table contains:
id, ..., file_1, desc_1, file_2, desc_2, date
What I need as a result is:
id, ..., file, desc, date
From both tables, which means I need to have coresponding file, desc and file_1 ->file, desc_1->desc and file_2->file, desc_2->desc in this one table.
Any idea how to do this with Zend 1.12?
You need to use JOIN in Zend ORM
for exmaple
public function getPendingProjects($owner){
$data = $this ->getAdapter()
->select()
->from('campaign' , array('title', 'id'))
->joinLeft('job', 'campaign.id = job.campaign_id', array('count(user_id)'))
->where('campaign.employer_id = ' . (int)$owner . ' AND job.status = 3' );
return $data->query()->fetchAll();
}
taked from here http://zend-frameworks.com/en/articles/zend_db_zend_mysql.html

MySQL order by IN array

I have a MySQL script like this: SELECT id, name FROM users WHERE id IN (6,4,34)
The sequence in the IN(...) array is very important. Is it possible to get them in the given sequence?
You can use the MySQL FIELD function to keep it compact;
SELECT id, name
FROM users
WHERE id IN (6, 4, 34)
ORDER BY FIELD(id, 6, 4, 34);
Try
SELECT id, name FROM users WHERE id IN (6,4,34) order by FIELD(id,6,4,34)
You can use any expression in the ORDER BY clause, including a 'CASE':
ORDER BY CASE id
WHEN 6 THEN 1
WHEN 4 THEN 2
WHEN 34 THEN 3
END ASC
If your list comes from the application programming layer, you might build this with the following (PHP here):
$sortVal = 1;
foreach($ids as $id_val) {
$cases[] = sprintf('WHEN %i THEN %i', $id_val, $sortVal++);
}
$order_by = 'ORDER BY CASE id ' . implode($cases) . ' END ASC';
However, I'll mention that Joachim's answer is quite elegant :-)
A complete example based on Chris Trahey answer.
$ids = array("table1", "table2", "table3");
$sortVal = 1;
foreach ($ids as $id_val) {
$cases[] = sprintf("WHEN '%s' THEN %u ", $id_val, $sortVal++);
}
$order_by = 'ORDER BY CASE `tableName` ' . implode($cases) . ' END ASC';
$result = mysqli_query( $con, "
SELECT DISTINCT tableName
FROM `table`
$order_by");