tags:

views:

50

answers:

2

Instead of executing 2 slightly different sql statements to get a total of 10 results can it be done with just one select?

e.g

select a , b , c from mytable limit 3

select a , b , LEFT(100, c ) from mytable limit 3, 10

+2  A: 

Check out UNION syntax

(SELECT a,b,c FROM mytable LIMIT 3)
UNION
(SELECT a,b,LEFT(100, c) FROM mytable LIMIT 3, 10);

Note the parentheses - these ensure the final LIMIT clause applies to the second query and not the whole result set.

Unless you've got a numeric key in the result which would let you use an IF to format the first n results differently, I don't think you're going to do this with a single select.

Paul Dixon
"one select" I should have stipulated "single trip to the database". Thank you!
A: 

You can select all ten rows and then use a case statement to control what value is returned depending on a conditional statement you define.
set @line_total= 0;

select
a,
b,
@line_total := @line_total + 1,
(case when @line_total < 4
then c
else left(100, c) end)
from test_query limit 10;


http://dev.mysql.com/doc/refman/5.0/en/case-statement.html

OG
Hope this sis the correct place to ask for clarification, but in place of [condition] in your example how can I generate some kind of 'counter' so I know I am on the 4th query?
I changed it to include a running total. However I'd recommend using a condition that is the reason that you want to use for an alternative statement, rather than a line number. When using sets it is bad practice to expect data to be in a particular order in the tables.
OG