Basically I do while two time to get main group & group value. Example
$group_query = $db->query("
SELECT opt_id, opt_type
FROM ads_options
WHERE opt_id = '" . intval($data['ad_id']) . "'
GROUP BY opt_type");
while ($group_data = $db->fetch($group_query)) {
$option_query = $db->query("
SELECT *
FROM ads_options
WHERE opt_id = '" . intval($data['ad_id']) . "'
AND opt_type ='" . $group_data['opt_type'] . "'
ORDER BY opt_id DESC");
while ($option_data = $db->fetch($option_query)) {
}
}
Output :
Size : S
M
L
Color : White
Black
Question :
How to join current queries above with single statement?
Update :
Current database structure
opt_id opt_type opt_name opt_price
1236 Size S 0
1236 Size M 1
1236 Color Black 1
1236 Color White 2
Something like this would get the unique combinations, may be of help
$group_query = $db->query("
SELECT
DISTINCT opt_id, opt_type, opt_size
FROM ads_options
WHERE opt_id = " . intval($data['ad_id']) . "
ORDER BY opt_type, opt_size");
If you are able to supply more details as to precisely what you are trying to achieve, and the full design of ads_options, then it would be easier to provide more specific advice
Also a minor note, if opt_id is numeric then you don't need single quotes (') around it within the query (so removed them in example)
EDIT
Something like the following would return you a list of id, type, and then as third field a comma-delimited list of values, if that's of more help
$group_query = $db->query("
SELECT
opt_id, opt_type, GROUP_CONCAT(opt_name) AS opt_names
FROM ads_options
WHERE opt_id = " . intval($data['ad_id']) . "
ORDER BY opt_type");
For more information on GROUP_CONCAT check out this link http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat
I've no idea if PHP programatically has something to help with this, I tend to use Coldfusion so if anyone knows of a PHP version of doing the following then that seems to match what OP was asking for
<cfoutput query="qryAdOptions" group="opt_type">
#qryAdOptions.opt_type#
<cfoutput>
#qryAdOptions.opt_name#
</cfoutput>
</cfoutput>
http://bytes.com/topic/php/answers/11929-grouping-results-query#post50606 seems to suggest the following as potentially a match for the I posted above so may be useful
$answer = array();
while ($row = pg_fetch_array($results)) {
if (!isset($answer[$row["obj_type"]])) {
$answer[$row["obj_type"]] = array();
}
$answer[$row["obj_type"]][] = $row;
}
You then iterate over $answer. This would play nicely with
SELECT * FROM ads_options WHERE opt_id = ......
Related
I have a terrible to identify unique record(value).
I have a table like this:
ID NAME DESCRIPTION
1 Yanagida Fumit best author
2 Ha Il-kwan new author
3 Fumit Yanagida best author
4 Ha Il Kwan new author
5 Ilkwan Ha new author
There are 5 records in same table called autho table. But in actually, there are 2 authors.
First record and third record are stored from one author information and second, 4th and 5th are one author.
I want to make this like below.
ID NAME DESCRIPTION
1 Yanagida Fumit best author
2 Ha Il Kwan new author
It means that, I am going to erase all duplicates against reverse name problem.
I wonder if I can compare two values(string) in same column.
Help me please. I will be happy with your any help!
Here is a php solution:
remove_duplicates("Yanagida Fumit");
function remove_duplicates($full_search_str) {
// establish connection to your db
// fetch data
$query = " SELECT `id`, `name`
FROM `" . $tbl_name . "`
WHERE MATCH (`name`) AGAINST ('" . $full_search_str . "' IN BOOLEAN MODE)
AND `name` <> '" . $full_search_str . "'
";
// run query
$results = $conn->query($query);
// loop through results
foreach($results as $result) {
// build query
$query = " DELETE
FROM `" . $tbl_name . "`
WHERE `id` = " . $result['id'];
// run query
$result = $conn->query($query);
}
}
Oracle answer:
create or replace table authors as
Select distinct name, description
from authors;
I have 2 tables
Table1
ID . Name . Position
= = = = = = = = = = = =
10 . Mike . Analyst
20 . Anna . HR
30 . Mark . Accountant
Table2
Deal ID . Status
= = = = = = = = = = = =
10 . . . . . Active
19 . . . . . New
20 . . . . . New
I want to add a new Calculated Column in Table1 with this logic :
If ID found in Table2 then return Position, ELSE return "NONE"
so the output table should be like this
Outout
ID . Name . Position . . . . **NewCol**
= = = = = = = = = = = = = = = = =
10 . Mike . Analyst . . . . . **Analyst**
20 . Anna . HR . . . . . . . . **HR**
30 . Mark . Accountant. . **NONE**
There are two ways to accomplish that.
Query Based Result
If you just want to display the information every time you need it, the simplest, cleanest and efficient way is just to perform a SELECT within the tables. In addition, the data will allways be updated, because the query runs over the actual table state.
So, the query would look like this:
SELECT T1.*, IF(T2.ID IS NULL, 'NONE', T1.Position) As NewPos
FROM Table1 T1 LEFT OUTER JOIN Table2 T2
ON (T1.ID = T2.ID)
This query will show the position if found on Table2 and, if not, it will display NULL value, so it may be useful for your needs.
Database Modification and Data Inserting
The other way, is to alter the Table1 structure to add the column Position. The existence of the column is referred to the table architecture, it is not value dependant, so you can't alter a Table and adding the column based on row values.
So, the first step to do is to alter the table adding the column, something like this:
ALTER TABLE table1 ADD COLUMN Position VARCHAR(50);
The second step is to fill the data. For this, you will have to perform an UPDATE to fill the data you have just created, something like this.
UPDATE Table1 T1 LEFT OUTER JOIN Table2 T2
ON (T1.ID = T2.ID)
SET T1.Position = IF(T2.ID IS NULL, 'NONE', T1.Position);
This query will update the rows which also exists in Table2 referenced by ID and will put its position.
The problem of this way it's that if you perform this and after, you add rows to Table1 and Table2, the information will not be updated and you'll have to do the UPDATE query every certain time, which is database and time cost.
So, if the application is not too big, in this case is better to use just the SELECT query, which involves less cost, performance and database changes.
i'm pulling my hair out here:
I have a sql statement that is part of an ajax call:
SELECT $wpdb->commentmeta.meta_value, $wpdb->comments.comment_ID, $wpdb->comments.comment_date, $wpdb->comments.user_id, $wpdb->comments.comment_content, $wpdb->comments.comment_author
FROM $wpdb->commentmeta
JOIN $wpdb->comments ON $wpdb->comments.comment_ID = $wpdb->commentmeta.comment_id
WHERE $wpdb->commentmeta.meta_key = '_commentsvote'
AND $wpdb->comments.comment_date >='" . $current_year . "-" . $current_month . "-01'
AND $wpdb->comments.comment_date <='" . $current_year . "-" . $current_month . "-31'
ORDER BY $wpdb->commentmeta.meta_value DESC
the statement works great, and returns results, however, the order is off. now, i know this is because the meta_value is actually a varchar, and not an int. so, the internets told me to do either a convert or cast:
Convert:
SELECT $wpdb->commentmeta.meta_value, $wpdb->comments.comment_ID, $wpdb->comments.comment_date, $wpdb->comments.user_id, $wpdb->comments.comment_content, $wpdb->comments.comment_author
FROM $wpdb->commentmeta
JOIN $wpdb->comments ON $wpdb->comments.comment_ID = $wpdb->commentmeta.comment_id
WHERE $wpdb->commentmeta.meta_key = '_commentsvote'
AND $wpdb->comments.comment_date >='" . $current_year . "-" . $current_month . "-01'
AND $wpdb->comments.comment_date <='" . $current_year . "-" . $current_month . "-31'
ORDER BY CONVERT(INT, $wpdb->commentmeta.meta_value) DESC
CAST
SELECT $wpdb->commentmeta.meta_value, $wpdb->comments.comment_ID, $wpdb->comments.comment_date, $wpdb->comments.user_id, $wpdb->comments.comment_content, $wpdb->comments.comment_author
FROM $wpdb->commentmeta
JOIN $wpdb->comments ON $wpdb->comments.comment_ID = $wpdb->commentmeta.comment_id
WHERE $wpdb->commentmeta.meta_key = '_commentsvote'
AND $wpdb->comments.comment_date >='" . $current_year . "-" . $current_month . "-01'
AND $wpdb->comments.comment_date <='" . $current_year . "-" . $current_month . "-31'
ORDER BY CAST($wpdb->commentmeta.meta_value AS INT) DESC
I keep getting sql errors on both of these when i run it as a sql statement (obviously, i convert the $wpdp to just say wp_) out of wordpress. the error is non specific - i.e. "you have an error near as int" for example.
so, two questions, first one is wp specific, and the second is a sql:
i'm pretty sure there's a way to write all this as an arg array i can pass into wp_query, but i'm unsure of how to do a join. code examples here would be super helpful.
why why WHY is this sql statement unwilling to convert that last colomn to an int?
Thanks Wp and SQL geniuses for reading!
The short version is that you can't CONVERT to INT - the proper type would be SIGNED. Read more about CAST and CONVERT. That said there are some other changes that you should make to make the code more readable and more secure.
First, if you use table aliases you cut down on the need to reference $wpdb so many times and it can make even more complex queries more readable (if you are joining to a meta table more than once on different keys for example).
More importantly you should use $wpdb->prepare() to escape your SQL - inserting variables into the statement is asking for a SQL injection. It probably also makes sense to leverage BETWEEN and DATE_ADD for your WHERE clause - not all months have 31 days. If you do want to pass in the start and end date, you should still use %s as a placeholder in the SQL and use prepare() to populate it.
global $wdbp;
$sql = <<<SQL
SELECT votes.meta_value, c.comment_ID, c.comment_date, c.user_id, c.comment_content, c.comment_author
FROM {$wpdb->comments} c
JOIN {$wpdb->commentmeta} votes
ON votes.comment_id = c.comment_ID AND votes.meta_key = '_commentsvote'
WHERE
c.comment_date BETWEEN %s AND DATE_ADD(%s, INTERVAL 1 MONTH)
ORDER BY CONVERT(votes.meta_value, SIGNED)
SQL;
$date = "{$current_year}-{$current_month}-01";
$query = $wpdb->prepare( $sql, $date, $date );
$results = $wpdb->get_results( $query );
I have created two tables as order & product.
In order table, order details are stored & in product table according to order, product details are stored. Now I want to give row no./line no. for that product table.
Say for order no. 100 there are 3 prodcuts-:
1 Nokia 8000 20
2 Samsung 5000 50
3 Sony 7000 30
So how to give row no/line no. for product in Mysql? Is there any function for the same?
And also that no. must start from 1 for each order.
Say after order no. 100, for order no. 101, it would be again start from 1,2...like this.
I have maintained proper PK & FK...like PK of order is FK for product table..
My Schema is like this-:
First I am inserting data in Order table using insert query so that will generate id i.e. mysql_insert_id() & I am using that for reference in Product table.
Now my code is like this-:
global $id;
$id = mysql_insert_id();
$query2 = "SELECT a.name, a.sku, a.qty_ordered, a.price, a.row_total, a.base_subtotal,
b.base_shipping_amount, b.base_grand_total,".$id."
FROM sales_flat_order b
JOIN sales_flat_order_item a
ON a.order_id = b.entity_id
WHERE b.increment_id = ". $order_id ;
$result2 = mysql_query($query2);
while($row = mysql_fetch_array($result2))
{
$result_str_product .= "('". $row["name"] . "',". "'" . $row["sku"] . "'," . "'" . $row["qty_ordered"] . "',". "'" . $row["price"] . "'," . "'" . $row["row_total"] . "'," . "'" . $row["base_subtotal"]. "'," . "'" . $row["base_shipping_amount"] . "'," . "'" . $row["base_grand_total"] ."',". $id."),";
}
$query3 = "INSERT into product(name, sku, qty_ordered, price, row_total, base_subtotal, base_shipping_amount,base_grand_total,prod_f) VALUES ".$result_str_product;
$final_result = substr_replace($query3,";",-1);
$result_query_product = mysql_query($final_result);
Now my requirement is that I want to generate line no./row no. for these products like I explain above(Plz chek my above example that Nokia,Samsung.
So How I can give row no./line no. for these item? Any in-built function for the same that I can use in while loop or any other approach?
I read here that I can include an argument inside COUNT, to return a calculated value. I'm trying the following but I'm missing something. Can you help? Thanks!
mysql_select_db(DATABASE_NAME, $connection);
$client = "demo/";
$result = mysql_query
(
"SELECT
COUNT(page_max > 126) AS completed
FROM " .SESSIONDB. "
WHERE client = '$client'
AND page = 'interaction.php'
"
);
if(mysql_error()) die(DIRECTORY_TITLE . " - Error DBA110 " . mysql_error());
// output THE QUERY
while($row = mysql_fetch_assoc($result))
{
echo $row['completed'];
}
Try
"SELECT
COUNT(*) AS completed
FROM " .SESSIONDB. "
WHERE client = '$client' AND page_max > 126
AND page = 'interaction.php'"
How about this
SELECT
SUM(CASE WHEN page_max > 126 THEN 1 ELSE 0 END) AS completed
FROM table
WHERE client = '$client'
AND page = 'interaction.php'
Or as Nicolò Martini said, move page_max to WHERE condition if you don't need total count of items.
This should do what you want:
SELECT COUNT(IF(page_max>126,1,NULL)) AS completed ....
COUNT counts the number of rows that aren't NULL. This expression turns anything where page_max is greater than 126 into 1 and anything that isn't into NULL.
That said, why not just move page_max to the WHERE condition?