Search Results

Search found 17240 results on 690 pages for 'query'.

Page 17/690 | < Previous Page | 13 14 15 16 17 18 19 20 21 22 23 24  | Next Page >

  • SQL SERVER – Fundamentals of Columnstore Index

    - by pinaldave
    There are two kind of storage in database. Row Store and Column Store. Row store does exactly as the name suggests – stores rows of data on a page – and column store stores all the data in a column on the same page. These columns are much easier to search – instead of a query searching all the data in an entire row whether the data is relevant or not, column store queries need only to search much lesser number of the columns. This means major increases in search speed and hard drive use. Additionally, the column store indexes are heavily compressed, which translates to even greater memory and faster searches. I am sure this looks very exciting and it does not mean that you convert every single index from row store to column store index. One has to understand the proper places where to use row store or column store indexes. Let us understand in this article what is the difference in Columnstore type of index. Column store indexes are run by Microsoft’s VertiPaq technology. However, all you really need to know is that this method of storing data is columns on a single page is much faster and more efficient. Creating a column store index is very easy, and you don’t have to learn new syntax to create them. You just need to specify the keyword “COLUMNSTORE” and enter the data as you normally would. Keep in mind that once you add a column store to a table, though, you cannot delete, insert or update the data – it is READ ONLY. However, since column store will be mainly used for data warehousing, this should not be a big problem. You can always use partitioning to avoid rebuilding the index. A columnstore index stores each column in a separate set of disk pages, rather than storing multiple rows per page as data traditionally has been stored. The difference between column store and row store approaches is illustrated below: In case of the row store indexes multiple pages will contain multiple rows of the columns spanning across multiple pages. In case of column store indexes multiple pages will contain multiple single columns. This will lead only the columns needed to solve a query will be fetched from disk. Additionally there is good chance that there will be redundant data in a single column which will further help to compress the data, this will have positive effect on buffer hit rate as most of the data will be in memory and due to same it will not need to be retrieved. Let us see small example of how columnstore index improves the performance of the query on a large table. As a first step let us create databaseset which is large enough to show performance impact of columnstore index. The time taken to create sample database may vary on different computer based on the resources. USE AdventureWorks GO -- Create New Table CREATE TABLE [dbo].[MySalesOrderDetail]( [SalesOrderID] [int] NOT NULL, [SalesOrderDetailID] [int] NOT NULL, [CarrierTrackingNumber] [nvarchar](25) NULL, [OrderQty] [smallint] NOT NULL, [ProductID] [int] NOT NULL, [SpecialOfferID] [int] NOT NULL, [UnitPrice] [money] NOT NULL, [UnitPriceDiscount] [money] NOT NULL, [LineTotal] [numeric](38, 6) NOT NULL, [rowguid] [uniqueidentifier] NOT NULL, [ModifiedDate] [datetime] NOT NULL ) ON [PRIMARY] GO -- Create clustered index CREATE CLUSTERED INDEX [CL_MySalesOrderDetail] ON [dbo].[MySalesOrderDetail] ( [SalesOrderDetailID]) GO -- Create Sample Data Table -- WARNING: This Query may run upto 2-10 minutes based on your systems resources INSERT INTO [dbo].[MySalesOrderDetail] SELECT S1.* FROM Sales.SalesOrderDetail S1 GO 100 Now let us do quick performance test. I have kept STATISTICS IO ON for measuring how much IO following queries take. In my test first I will run query which will use regular index. We will note the IO usage of the query. After that we will create columnstore index and will measure the IO of the same. -- Performance Test -- Comparing Regular Index with ColumnStore Index USE AdventureWorks GO SET STATISTICS IO ON GO -- Select Table with regular Index SELECT ProductID, SUM(UnitPrice) SumUnitPrice, AVG(UnitPrice) AvgUnitPrice, SUM(OrderQty) SumOrderQty, AVG(OrderQty) AvgOrderQty FROM [dbo].[MySalesOrderDetail] GROUP BY ProductID ORDER BY ProductID GO -- Table 'MySalesOrderDetail'. Scan count 1, logical reads 342261, physical reads 0, read-ahead reads 0. -- Create ColumnStore Index CREATE NONCLUSTERED COLUMNSTORE INDEX [IX_MySalesOrderDetail_ColumnStore] ON [MySalesOrderDetail] (UnitPrice, OrderQty, ProductID) GO -- Select Table with Columnstore Index SELECT ProductID, SUM(UnitPrice) SumUnitPrice, AVG(UnitPrice) AvgUnitPrice, SUM(OrderQty) SumOrderQty, AVG(OrderQty) AvgOrderQty FROM [dbo].[MySalesOrderDetail] GROUP BY ProductID ORDER BY ProductID GO It is very clear from the results that query is performance extremely fast after creating ColumnStore Index. The amount of the pages it has to read to run query is drastically reduced as the column which are needed in the query are stored in the same page and query does not have to go through every single page to read those columns. If we enable execution plan and compare we can see that column store index performance way better than regular index in this case. Let us clean up the database. -- Cleanup DROP INDEX [IX_MySalesOrderDetail_ColumnStore] ON [dbo].[MySalesOrderDetail] GO TRUNCATE TABLE dbo.MySalesOrderDetail GO DROP TABLE dbo.MySalesOrderDetail GO In future posts we will see cases where Columnstore index is not appropriate solution as well few other tricks and tips of the columnstore index. Reference: Pinal Dave (http://blog.SQLAuthority.com) Filed under: Pinal Dave, PostADay, SQL, SQL Authority, SQL Index, SQL Optimization, SQL Performance, SQL Query, SQL Scripts, SQL Server, SQL Tips and Tricks, T SQL, Technology

    Read the article

  • MySQL enters another value that the one given by PHP

    - by Tristan
    Hello, The big problem : mysql does not stores the information i told him to via PHP Example (this req is an echo just before the query) : INSERT INTO serveur (GSP_nom , IPserv, port, tickrate, membre, nomPays, finContrat, type, jeux, slot, ipClient, email) VALUES ( 'ckras', '88.191.88.57', '37060', '100' , '', 'Allemagne','20110519', '2', '4','99' ,'82.220.201.183','[email protected]'); But on the MySQL i have : 403 ckras 88.191.88.57 32767 100 Allemagne 20110519 1 2010-04-25 00:51:47 2 4 99 82.220.201.183 [email protected] port : 37060 (right value) //// 32767 (MySQL's drug?) Any help would be appreciated, i'm worse than stuck and i'm ** off PS: *There is no trigger on the mysql as far as i know / there is no controll on the port which means that nowhere i modify the "port" value and this script works for 80% of the time ( it seems that as soon as the users enters a port = 30000 it causes that bug), an user first reported to me this error today and the script was running since 3 months* Thanks

    Read the article

  • Trouble with a query

    - by Mark Allison
    Hi there, I'm having trouble with a query in SQL Server 2008 on some forex trading data. I have a trades table and an orders table. A trade needs to comprise of 2 or more orders. DDL schema and sample data below. What I want to do is write a query that shows the profit/loss in pips for each trade. A pip is 1/1000th of a currency. So the difference between USD 1.3441 and 1.3442 is 1 pip in forex-speak. A trade usually has one entry order and multiple exit orders. So for example if I buy 3 lots of the currency pair GBP/USD at the exchange rate of 1.6100 and then sell 1 lot at 1.6150, 1 lot at 1.6200 and 1 lot at 1.6250 then the profit is (1.6150 - 1.6100) + (1.6200 - 1.6100) + (1.6250 - 1.6100), or 50 + 100 + 150 = 300 pips profit. The trade could also go the other way (Shorting). For example the currency pair can be sold first before it's bought back later at a cheaper price. I would like a query that returns the following: tradeId, currencyPair, profitInPips It seems like a pretty straightforward query, but it's eluding me right now. Here's my DDL and sample data: CREATE TABLE [dbo].[trades]( [tradeId] [int] IDENTITY(1,1) NOT NULL, [currencyPair] [char](6) NOT NULL, CONSTRAINT [PK_trades] PRIMARY KEY CLUSTERED ( [tradeId] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO SET ANSI_PADDING OFF GO SET IDENTITY_INSERT [dbo].[trades] ON INSERT [dbo].[trades] ([tradeId], [currencyPair]) VALUES (1, N'GBPUSD') INSERT [dbo].[trades] ([tradeId], [currencyPair]) VALUES (2, N'GBPUSD') INSERT [dbo].[trades] ([tradeId], [currencyPair]) VALUES (3, N'GBPUSD') INSERT [dbo].[trades] ([tradeId], [currencyPair]) VALUES (4, N'GBPUSD') INSERT [dbo].[trades] ([tradeId], [currencyPair]) VALUES (5, N'GBPUSD') INSERT [dbo].[trades] ([tradeId], [currencyPair]) VALUES (6, N'GBPUSD') INSERT [dbo].[trades] ([tradeId], [currencyPair]) VALUES (7, N'GBPUSD') INSERT [dbo].[trades] ([tradeId], [currencyPair]) VALUES (8, N'GBPUSD') INSERT [dbo].[trades] ([tradeId], [currencyPair]) VALUES (9, N'GBPUSD') INSERT [dbo].[trades] ([tradeId], [currencyPair]) VALUES (10, N'GBPUSD') SET IDENTITY_INSERT [dbo].[trades] OFF GO CREATE TABLE [dbo].[orders]( [orderId] [int] IDENTITY(1,1) NOT NULL, [tradeId] [int] NOT NULL, [amount] [decimal](18, 1) NOT NULL, [buySell] [char](1) NOT NULL, [rate] [decimal](18, 6) NOT NULL, [orderDateTime] [datetime] NOT NULL, CONSTRAINT [PK_orders] PRIMARY KEY CLUSTERED ( [orderId] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO SET ANSI_PADDING OFF GO SET IDENTITY_INSERT [dbo].[orders] ON INSERT [dbo].[orders] ([orderId], [tradeId], [amount], [buySell], [rate], [orderDateTime]) VALUES (1, 1, CAST(3.0 AS Decimal(18, 1)), N'S', CAST(1.606500 AS Decimal(18, 6)), CAST(0x00009CF40083D600 AS DateTime)) INSERT [dbo].[orders] ([orderId], [tradeId], [amount], [buySell], [rate], [orderDateTime]) VALUES (2, 1, CAST(3.0 AS Decimal(18, 1)), N'B', CAST(1.615500 AS Decimal(18, 6)), CAST(0x00009CF400A4CB80 AS DateTime)) INSERT [dbo].[orders] ([orderId], [tradeId], [amount], [buySell], [rate], [orderDateTime]) VALUES (3, 2, CAST(3.0 AS Decimal(18, 1)), N'S', CAST(1.608000 AS Decimal(18, 6)), CAST(0x00009CF500000000 AS DateTime)) INSERT [dbo].[orders] ([orderId], [tradeId], [amount], [buySell], [rate], [orderDateTime]) VALUES (4, 2, CAST(1.0 AS Decimal(18, 1)), N'B', CAST(1.603000 AS Decimal(18, 6)), CAST(0x00009CF50083D600 AS DateTime)) INSERT [dbo].[orders] ([orderId], [tradeId], [amount], [buySell], [rate], [orderDateTime]) VALUES (5, 2, CAST(2.0 AS Decimal(18, 1)), N'B', CAST(1.605500 AS Decimal(18, 6)), CAST(0x00009CF50107AC00 AS DateTime)) INSERT [dbo].[orders] ([orderId], [tradeId], [amount], [buySell], [rate], [orderDateTime]) VALUES (6, 3, CAST(3.0 AS Decimal(18, 1)), N'S', CAST(1.595500 AS Decimal(18, 6)), CAST(0x00009CF70083D600 AS DateTime)) INSERT [dbo].[orders] ([orderId], [tradeId], [amount], [buySell], [rate], [orderDateTime]) VALUES (7, 3, CAST(1.0 AS Decimal(18, 1)), N'B', CAST(1.590500 AS Decimal(18, 6)), CAST(0x00009CF700C5C100 AS DateTime)) INSERT [dbo].[orders] ([orderId], [tradeId], [amount], [buySell], [rate], [orderDateTime]) VALUES (8, 3, CAST(2.0 AS Decimal(18, 1)), N'B', CAST(1.594500 AS Decimal(18, 6)), CAST(0x00009CF701499700 AS DateTime)) INSERT [dbo].[orders] ([orderId], [tradeId], [amount], [buySell], [rate], [orderDateTime]) VALUES (9, 4, CAST(3.0 AS Decimal(18, 1)), N'B', CAST(1.611000 AS Decimal(18, 6)), CAST(0x00009CFB0083D600 AS DateTime)) INSERT [dbo].[orders] ([orderId], [tradeId], [amount], [buySell], [rate], [orderDateTime]) VALUES (10, 4, CAST(1.0 AS Decimal(18, 1)), N'S', CAST(1.616000 AS Decimal(18, 6)), CAST(0x00009CFB00A4CB80 AS DateTime)) INSERT [dbo].[orders] ([orderId], [tradeId], [amount], [buySell], [rate], [orderDateTime]) VALUES (11, 4, CAST(2.0 AS Decimal(18, 1)), N'S', CAST(1.611500 AS Decimal(18, 6)), CAST(0x00009CFB0107AC00 AS DateTime)) INSERT [dbo].[orders] ([orderId], [tradeId], [amount], [buySell], [rate], [orderDateTime]) VALUES (12, 5, CAST(3.0 AS Decimal(18, 1)), N'B', CAST(1.613000 AS Decimal(18, 6)), CAST(0x00009CFC0083D600 AS DateTime)) INSERT [dbo].[orders] ([orderId], [tradeId], [amount], [buySell], [rate], [orderDateTime]) VALUES (13, 5, CAST(1.0 AS Decimal(18, 1)), N'S', CAST(1.618000 AS Decimal(18, 6)), CAST(0x00009CFC0107AC00 AS DateTime)) INSERT [dbo].[orders] ([orderId], [tradeId], [amount], [buySell], [rate], [orderDateTime]) VALUES (14, 5, CAST(1.0 AS Decimal(18, 1)), N'S', CAST(1.623000 AS Decimal(18, 6)), CAST(0x00009CFC0083D600 AS DateTime)) INSERT [dbo].[orders] ([orderId], [tradeId], [amount], [buySell], [rate], [orderDateTime]) VALUES (15, 5, CAST(1.0 AS Decimal(18, 1)), N'S', CAST(1.628000 AS Decimal(18, 6)), CAST(0x00009CFD00C5C100 AS DateTime)) INSERT [dbo].[orders] ([orderId], [tradeId], [amount], [buySell], [rate], [orderDateTime]) VALUES (16, 6, CAST(3.0 AS Decimal(18, 1)), N'B', CAST(1.632000 AS Decimal(18, 6)), CAST(0x00009D020083D600 AS DateTime)) INSERT [dbo].[orders] ([orderId], [tradeId], [amount], [buySell], [rate], [orderDateTime]) VALUES (17, 6, CAST(1.0 AS Decimal(18, 1)), N'S', CAST(1.637000 AS Decimal(18, 6)), CAST(0x00009D0200A4CB80 AS DateTime)) INSERT [dbo].[orders] ([orderId], [tradeId], [amount], [buySell], [rate], [orderDateTime]) VALUES (18, 6, CAST(2.0 AS Decimal(18, 1)), N'S', CAST(1.630000 AS Decimal(18, 6)), CAST(0x00009D0200C5C100 AS DateTime)) INSERT [dbo].[orders] ([orderId], [tradeId], [amount], [buySell], [rate], [orderDateTime]) VALUES (19, 7, CAST(3.0 AS Decimal(18, 1)), N'B', CAST(1.634500 AS Decimal(18, 6)), CAST(0x00009D0201499700 AS DateTime)) INSERT [dbo].[orders] ([orderId], [tradeId], [amount], [buySell], [rate], [orderDateTime]) VALUES (20, 7, CAST(1.0 AS Decimal(18, 1)), N'S', CAST(1.639500 AS Decimal(18, 6)), CAST(0x00009D0300000000 AS DateTime)) INSERT [dbo].[orders] ([orderId], [tradeId], [amount], [buySell], [rate], [orderDateTime]) VALUES (21, 7, CAST(1.0 AS Decimal(18, 1)), N'S', CAST(1.644500 AS Decimal(18, 6)), CAST(0x00009D030083D600 AS DateTime)) INSERT [dbo].[orders] ([orderId], [tradeId], [amount], [buySell], [rate], [orderDateTime]) VALUES (22, 7, CAST(1.0 AS Decimal(18, 1)), N'S', CAST(1.637500 AS Decimal(18, 6)), CAST(0x00009D0300C5C100 AS DateTime)) INSERT [dbo].[orders] ([orderId], [tradeId], [amount], [buySell], [rate], [orderDateTime]) VALUES (23, 8, CAST(3.0 AS Decimal(18, 1)), N'S', CAST(1.625000 AS Decimal(18, 6)), CAST(0x00009D0400C5C100 AS DateTime)) INSERT [dbo].[orders] ([orderId], [tradeId], [amount], [buySell], [rate], [orderDateTime]) VALUES (24, 8, CAST(1.0 AS Decimal(18, 1)), N'B', CAST(1.620000 AS Decimal(18, 6)), CAST(0x00009D050083D600 AS DateTime)) INSERT [dbo].[orders] ([orderId], [tradeId], [amount], [buySell], [rate], [orderDateTime]) VALUES (25, 8, CAST(1.0 AS Decimal(18, 1)), N'B', CAST(1.615000 AS Decimal(18, 6)), CAST(0x00009D0500A4CB80 AS DateTime)) INSERT [dbo].[orders] ([orderId], [tradeId], [amount], [buySell], [rate], [orderDateTime]) VALUES (26, 8, CAST(1.0 AS Decimal(18, 1)), N'S', CAST(1.623000 AS Decimal(18, 6)), CAST(0x00009D050107AC00 AS DateTime)) INSERT [dbo].[orders] ([orderId], [tradeId], [amount], [buySell], [rate], [orderDateTime]) VALUES (27, 9, CAST(3.0 AS Decimal(18, 1)), N'S', CAST(1.618000 AS Decimal(18, 6)), CAST(0x00009D0600C5C100 AS DateTime)) INSERT [dbo].[orders] ([orderId], [tradeId], [amount], [buySell], [rate], [orderDateTime]) VALUES (28, 9, CAST(1.0 AS Decimal(18, 1)), N'B', CAST(1.613000 AS Decimal(18, 6)), CAST(0x00009D0600D63BC0 AS DateTime)) INSERT [dbo].[orders] ([orderId], [tradeId], [amount], [buySell], [rate], [orderDateTime]) VALUES (29, 9, CAST(1.0 AS Decimal(18, 1)), N'B', CAST(1.608000 AS Decimal(18, 6)), CAST(0x00009D0600E6B680 AS DateTime)) INSERT [dbo].[orders] ([orderId], [tradeId], [amount], [buySell], [rate], [orderDateTime]) VALUES (30, 9, CAST(1.0 AS Decimal(18, 1)), N'B', CAST(1.613300 AS Decimal(18, 6)), CAST(0x00009D0601391C40 AS DateTime)) INSERT [dbo].[orders] ([orderId], [tradeId], [amount], [buySell], [rate], [orderDateTime]) VALUES (31, 10, CAST(3.0 AS Decimal(18, 1)), N'B', CAST(1.614500 AS Decimal(18, 6)), CAST(0x00009D090083D600 AS DateTime)) INSERT [dbo].[orders] ([orderId], [tradeId], [amount], [buySell], [rate], [orderDateTime]) VALUES (32, 10, CAST(1.0 AS Decimal(18, 1)), N'S', CAST(1.619500 AS Decimal(18, 6)), CAST(0x00009D090107AC00 AS DateTime)) INSERT [dbo].[orders] ([orderId], [tradeId], [amount], [buySell], [rate], [orderDateTime]) VALUES (33, 10, CAST(1.0 AS Decimal(18, 1)), N'S', CAST(1.624500 AS Decimal(18, 6)), CAST(0x00009D0901499700 AS DateTime)) INSERT [dbo].[orders] ([orderId], [tradeId], [amount], [buySell], [rate], [orderDateTime]) VALUES (34, 10, CAST(1.0 AS Decimal(18, 1)), N'S', CAST(1.619000 AS Decimal(18, 6)), CAST(0x00009D0A0083D600 AS DateTime)) SET IDENTITY_INSERT [dbo].[orders] OFF /****** Object: ForeignKey [FK_orders_trades] Script Date: 04/02/2010 15:05:31 ******/ ALTER TABLE [dbo].[orders] WITH CHECK ADD CONSTRAINT [FK_orders_trades] FOREIGN KEY([tradeId]) REFERENCES [dbo].[trades] ([tradeId]) GO ALTER TABLE [dbo].[orders] CHECK CONSTRAINT [FK_orders_trades] GO Thanks in advance for any help!

    Read the article

  • NHibernate query with Projections.Cast to DateTime

    - by stiank81
    I'm experimenting with using a string for storing different kind of data types in a database. When I do queries I need to cast the strings to the right type in the query itself. I'm using .Net with NHibernate, and was glad to learn that there exists functionality for this. Consider the simple class: public class Foo { public string Text { get; set; } } I successfully use Projections.Cast to cast to numeric values, e.g. the following query correctly returns all Foos with an interger stored as int - between 1-10. var result = Session.CreateCriteria<Foo>() .Add(Restrictions.Between(Projections.Cast(NHibernateUtil.Int32, Projections.Property("Text")), 1, 10)) .List<Foo>(); Now if I try using this for DateTime I'm not able to make it work no matter what I try. Why?! var date = new DateTime(2010, 5, 21, 11, 30, 00); AddFooToDb(new Foo { Text = date.ToString() } ); // Will add it to the database... var result = Session .CreateCriteria<Foo>() .Add(Restrictions.Eq(Projections.Cast(NHibernateUtil.DateTime, Projections.Property("Text")), date)) .List<Foo>();

    Read the article

  • MySql query optimization help

    - by rohitgu
    I have few queries and am not able to figure out how to optimize them, QUERY 1 select * from t_twitter_tracking where classified is null and tweetType='ENGLISH' order by id limit 500; QUERY 2 Select count(*) as cnt, DATE_FORMAT(CONVERT_TZ(wrdTrk.createdOnGMTDate,'+00:00','+05:30'),'%Y-%m-%d') as dat from t_twitter_tracking wrdTrk where wrdTrk.word like ('dell') and CONVERT_TZ(wrdTrk.createdOnGMTDate,'+00:00','+05:30') between '2010-12-12 00:00:00' and '2010-12-26 00:00:00' group by dat; Both these queries run on the same table, CREATE TABLE `t_twitter_tracking` ( `id` BIGINT(20) NOT NULL AUTO_INCREMENT, `word` VARCHAR(200) NOT NULL, `tweetId` BIGINT(100) NOT NULL, `twtText` VARCHAR(800) NULL DEFAULT NULL, `language` TEXT NULL, `links` TEXT NULL, `tweetType` VARCHAR(20) NULL DEFAULT NULL, `source` TEXT NULL, `sourceStripped` TEXT NULL, `isTruncated` VARCHAR(40) NULL DEFAULT NULL, `inReplyToStatusId` BIGINT(30) NULL DEFAULT NULL, `inReplyToUserId` INT(11) NULL DEFAULT NULL, `rtUsrProfilePicUrl` TEXT NULL, `isFavorited` VARCHAR(40) NULL DEFAULT NULL, `inReplyToScreenName` VARCHAR(40) NULL DEFAULT NULL, `latitude` BIGINT(100) NOT NULL, `longitude` BIGINT(100) NOT NULL, `retweetedStatus` VARCHAR(40) NULL DEFAULT NULL, `statusInReplyToStatusId` BIGINT(100) NOT NULL, `statusInReplyToUserId` BIGINT(100) NOT NULL, `statusFavorited` VARCHAR(40) NULL DEFAULT NULL, `statusInReplyToScreenName` TEXT NULL, `screenName` TEXT NULL, `profilePicUrl` TEXT NULL, `twitterId` BIGINT(100) NOT NULL, `name` TEXT NULL, `location` VARCHAR(100) NULL DEFAULT NULL, `bio` TEXT NULL, `url` TEXT NULL COLLATE 'latin1_swedish_ci', `utcOffset` INT(11) NULL DEFAULT NULL, `timeZone` VARCHAR(100) NULL DEFAULT NULL, `frenCnt` BIGINT(20) NULL DEFAULT '0', `createdAt` DATETIME NULL DEFAULT NULL, `createdOnGMT` VARCHAR(40) NULL DEFAULT NULL, `createdOnServerTime` DATETIME NULL DEFAULT NULL, `follCnt` BIGINT(20) NULL DEFAULT '0', `favCnt` BIGINT(20) NULL DEFAULT '0', `totStatusCnt` BIGINT(20) NULL DEFAULT NULL, `usrCrtDate` VARCHAR(200) NULL DEFAULT NULL, `humanSentiment` VARCHAR(30) NULL DEFAULT NULL, `replied` BIT(1) NULL DEFAULT NULL, `replyMsg` TEXT NULL, `classified` INT(32) NULL DEFAULT NULL, `createdOnGMTDate` DATETIME NULL DEFAULT NULL, `locationDetail` TEXT NULL, `geonameid` INT(11) NULL DEFAULT NULL, `country` VARCHAR(255) NULL DEFAULT NULL, `continent` CHAR(2) NULL DEFAULT NULL, `placeLongitude` FLOAT NULL DEFAULT NULL, `placeLatitude` FLOAT NULL DEFAULT NULL, PRIMARY KEY (`id`), INDEX `id` (`id`, `word`), INDEX `createdOnGMT_index` (`createdOnGMT`) USING BTREE, INDEX `word_index` (`word`) USING BTREE, INDEX `location_index` (`location`) USING BTREE, INDEX `classified_index` (`classified`) USING BTREE, INDEX `tweetType_index` (`tweetType`) USING BTREE, INDEX `getunclassified_index` (`classified`, `tweetType`) USING BTREE, INDEX `timeline_index` (`word`, `createdOnGMTDate`, `classified`) USING BTREE, INDEX `createdOnGMTDate_index` (`createdOnGMTDate`) USING BTREE, INDEX `locdetail_index` (`country`, `id`) USING BTREE, FULLTEXT INDEX `twtText_index` (`twtText`) ) COLLATE='utf8_general_ci' ENGINE=MyISAM ROW_FORMAT=DEFAULT AUTO_INCREMENT=12608048; The table has more than 10 million records. How can I optimize it?

    Read the article

  • Hibernate - query caching/second level cache does not work by value object containing subitems

    - by Zoltan Hamori
    Hi! I have been struggling with the following problem: I have a value object containing different panels. Each panel has a list of fields. Mapping: <class name="com.aviseurope.core.application.RACountryPanels" table="CTRY" schema="DBDEV1A" where="PEARL_CTRY='Y'" lazy="join"> <cache usage="read-only"/> <id name="ctryCode"> <column name="CTRY_CD_ID" sql-type="VARCHAR2(2)" not-null="true"/> </id> <bag name="panelPE" table="RA_COUNTRY_MAPPING" fetch="join" where="MANDATORY_FLAG!='N'"> <key column="COUNTRY_LOCATION_ID"/> <many-to-many class="com.aviseurope.core.application.RAFieldVO" column="RA_FIELD_MID" where="PANEL_ID='PE'"/> </bag> </class> I use the following criteria to get the value object: Session m_Session = HibernateUtil.currentSession(); m_Criteria = m_Session.createCriteria(RACountryPanels.class); m_Criteria.add(Expression.eq("ctryCode", p_Country)); m_Criteria.setCacheable(true); As I see the query cache contains only the main select like select * from CTRY where ctry_cd_id=? Both RACountryPanels and RAFieldVO are second level cached. If I check the 2nd level cache content I can see that it cointains the RAFields and the RACountryPanels as well and I can see the select .. from CTRY where ctry_cd_id=... in query cache region as well. When I call the servlet it seems that it is using the cache, but second time not. If I check the content of the cache using JMX, everything seems to be ok, but when I measure the object access time, it seems that it does not always use the cache. Cheers Zoltan

    Read the article

  • LDAP Query with sub result

    - by StefanE
    I have been banging my head for quite a while with this and can't get it to work. I have a LDAP Query I do have working in AD Users and Computers but dont know how to do it programatically in C#. Here are my LDAP Query that works fine in the AD Tool: (memberOf=CN=AccRght,OU=Groups,OU=P,OU=Server,DC=mydomain,DC=com)(objectCategory=user)(objectClass=user)(l=City) I have used this code to get the user accounts to get members of CN=AccRght but I'm not succeeding on limiting users belonging to a specific city. public StringCollection GetGroupMembers(string strDomain, string strGroup) { StringCollection groupMemebers = new StringCollection(); try { DirectoryEntry ent = new DirectoryEntry("LDAP://DC=" + strDomain + ",DC=com"); DirectorySearcher srch = new DirectorySearcher("(CN=" + strGroup + ")"); SearchResultCollection coll = srch.FindAll(); foreach (SearchResult rs in coll) { ResultPropertyCollection resultPropColl = rs.Properties; foreach( Object memberColl in resultPropColl["member"]) { DirectoryEntry gpMemberEntry = new DirectoryEntry("LDAP://" + memberColl); System.DirectoryServices.PropertyCollection userProps = gpMemberEntry.Properties; object obVal = userProps["sAMAccountName"].Value; if (null != obVal) { groupMemebers.Add(obVal.ToString()); } } } } catch (Exception ex) { Console.Write(ex.Message); } return groupMemebers; } Thanks for any help!

    Read the article

  • Require help in Writing Query

    - by harigm
    The following image have been uploaded to show what I am trying to do and what I wanted out of it Can any one help me write the Query to get the results what I want Please check the following SELECT * FROM KPT WHERE PROPERTY_ID IN (SELECT PROPERTY_ID FROM khata_header WHERE DIV_ID = 3 and RECORD_STATUS = 0) and CHALLAN_NO > 42646 The above is the query I have written and I have got the following result set ID CHALLAN_NO PROPERTY_ID SITE_NO TOTAL_AMOUNT ----- ------------- -------------- ------------------- --------------- 1242 42757 3103010141 296 595 1243 63743 3204190257 483 594 1244 63743 3204190257 483 594 1334 43395 3217010223 1088 576 1421 524210 3320050416 (null) (null) 1422 524210 3320050416 (null) (null) 1560 564355 3320021408 (null) (null) 1870 516292 3320040420 (null) (null) 1940 68357 3217100104 139 1153 1941 68357 3217100104 139 1153 2002 56256 3320100733 511 4430 2003 56256 3320100733 511 4430 2004 66488 3217040869 293 3094 2005 66488 3217040869 293 3094 2016 64571 3217040374 (null) (null) 2036 523122 3320020352 (null) (null) 2039 65682 3217040021 273 919 In my resultset, I am getting the PropertyId repeated, since there are multilple entries, How Can I know How many have been repeated What are those Property Id which have repeated more than 2 times. Little Back ground about the tables are PROPERTY_ID is the FK in the KPT PROPERTY_ID is the PK in KH I am writing a subquery to get the Result, so I am stuck I dont know how to get my results Please help

    Read the article

  • SQL query using information from 4 tables (not all directly linked)

    - by Yvonne
    I'm developing a simple classroom system, where teachers manage classes and their subjects. I have 2 levels of access in my teachers table, assigned by an integer (1 = admin, 2 = user)... Meaning that the headteacher is the admin :) A teacher (of level 1) can have have many classes and a class can have many teachers (so I have 'TeachersClasses' table). A class can have many subjects, and a teacher can have many subjects. Basically, I'm attempting a query to display the admin teacher's (level 1) subjects. However, only teachers with a level of 2, are directly related to a subject, which is set by the admin user. The headteacher can view all of their subjects via the classroom, but I cannot get all of the subjects to be displayed on one page, instead I can only get the subjects to appear under a specific classroom right now... This is what I have so far, which is returning nothing. (I'm guessing this may require an SQL clause more advanced that 'INNER JOIN' which is the only join type I am familiar with, and thought it would be enough! $query = "SELECT subjects.subjectid, subjects.subjectname, subjects.subjectdetails, classroom.classid, classroom.classname FROM subjects INNER JOIN classroom ON subjects.subjectid = classroom.classid INNER JOIN teacherclasses ON classroom.classid = teacherclasses.classid INNER JOIN teachers ON teacherclasses.teacherid = teachers.teacherid WHERE teachers.teacherid = '".intval( $_SESSION['SESS_TEACHERID'] )."'"; In order for all subjects related to the headteachers class to be displayed, I'm gathering that all of my tables will need to be called up here? Thanks for any help! Example output: subject name: maths // teacher: mr smith // classroom: DG99 x10 for all the subjects associated with the headteachers classrooms :)

    Read the article

  • SQL Query Returning Duplicate Results

    - by Jesse Bunch
    Hi, I've been working out this query now for a while and I thought I had it where I wanted it, but apparently not. There are two records in the database (orders). The query should return two different rows, but instead returns two rows that have exactly the same values. I think it may be something to do with the GROUP BY or derived tables I'm using but my eyes are tired and not seeing the problem. Can any of you help? Thanks in advance. SELECT orders.billerID, orders.invoiceDate, orders.txnID, orders.bName, orders.bStreet1, orders.bStreet2, orders.bCity, orders.bState, orders.bZip, orders.bCountry, orders.sName, orders.sStreet1, orders.sStreet2, orders.sCity, orders.sState, orders.sZip, orders.sCountry, orders.paymentType, orders.invoiceNotes, orders.pFee, orders.shipping, orders.tax, orders.reasonCode, orders.txnType, orders.customerID, customers.firstName AS firstName, customers.lastName AS lastName, customers.businessName AS businessName, orderStatus.statusName AS orderStatus, IFNULL(orderItems.itemTotal, 0.00) + orders.shipping + orders.tax AS orderTotal, IFNULL(orderItems.itemTotal, 0.00) + orders.shipping + orders.tax - IFNULL(payments.totalPayments, 0.00) AS orderBalance FROM orders LEFT JOIN customers ON orders.customerID = customers.id LEFT JOIN orderStatus ON orders.orderStatus = orderStatus.id LEFT JOIN ( SELECT orderItems.orderID, SUM(orderItems.itemPrice * orderItems.itemQuantity) as itemTotal FROM orderItems GROUP BY orderItems.orderID ) orderItems ON orderItems.orderID = orders.id LEFT JOIN ( SELECT payments.orderID, SUM(payments.amount) as totalPayments FROM payments GROUP BY payments.orderID ) payments ON payments.orderID = orders.id

    Read the article

  • Query to MySQL from c# returns System.Byte[]

    - by karthik
    I am using the below SP to return the value of Generated Insert statement and it works fine when executed in Query browser. When i try to get the value from C#, it give's me "System.Byte[]" as return value. When i try to get the value from MySql query browser, it give's me return value as : 'insert into admindb.accounts values("54321","2","karthik2","karthik2","1");' I guess the problem is with the single quotes of the returned value. Is it so ? DELIMITER $$ DROP PROCEDURE IF EXISTS `admindb`.`InsGen` $$ CREATE DEFINER=`root`@`localhost` PROCEDURE `InsGen`( in_db varchar(20), in_table varchar(20), in_ColumnName varchar(20), in_ColumnValue varchar(20) ) BEGIN declare Whrs varchar(500); declare Sels varchar(500); declare Inserts varchar(2000); declare tablename varchar(20); declare ColName varchar(20); set tablename=in_table; # Comma separated column names - used for Select select group_concat(concat('concat(\'"\',','ifnull(',column_name,','''')',',\'"\')')) INTO @Sels from information_schema.columns where table_schema=in_db and table_name=tablename; # Comma separated column names - used for Group By select group_concat('`',column_name,'`') INTO @Whrs from information_schema.columns where table_schema=in_db and table_name=tablename; #Main Select Statement for fetching comma separated table values set @Inserts=concat("select concat('insert into ", in_db,".",tablename," values(',concat_ws(',',",@Sels,"),');') as MyColumn from ", in_db,".",tablename, " where ", in_ColumnName, " = " , in_ColumnValue, " group by ",@Whrs, ";"); PREPARE Inserts FROM @Inserts; EXECUTE Inserts; END $$ DELIMITER ;

    Read the article

  • Avoiding secondary selects or joins with Hibernate Criteria or HQL query

    - by Ben Benson
    I am having trouble optimizing Hibernate queries to avoid performing joins or secondary selects. When a Hibernate query is performed (criteria or hql), such as the following: return getSession().createQuery(("from GiftCard as card where card.recipientNotificationRequested=1").list(); ... and the where clause examines properties that do not require any joins with other tables... but Hibernate still performs a full join with other tables (or secondary selects depending on how I set the fetchMode). The object in question (GiftCard) has a couple ManyToOne associations that I would prefer to be lazily loaded in this case (but not necessarily all cases). I want a solution that I can control what is lazily loaded when I perform the query. Here's what the GiftCard Entity looks like: @Entity @Table(name = "giftCards") public class GiftCard implements Serializable { private static final long serialVersionUID = 1L; private String id_; private User buyer_; private boolean isRecipientNotificationRequested_; @Id public String getId() { return this.id_; } public void setId(String id) { this.id_ = id; } @ManyToOne @JoinColumn(name = "buyerUserId") @NotFound(action = NotFoundAction.IGNORE) public User getBuyer() { return this.buyer_; } public void setBuyer(User buyer) { this.buyer_ = buyer; } @Column(name="isRecipientNotificationRequested", nullable=false, columnDefinition="tinyint") public boolean isRecipientNotificationRequested() { return this.isRecipientNotificationRequested_; } public void setRecipientNotificationRequested(boolean isRecipientNotificationRequested) { this.isRecipientNotificationRequested_ = isRecipientNotificationRequested; } }

    Read the article

  • Yahoo Query Language Problem

    - by Damiano
    Hello everybody! Today, I've started with Yahoo Query Language. I would use it to retrive stocks details, so I'm talking about Yahoo Finance. I think there is a bug on this language. This is my query: select * from yahoo.finance.quoteslist where symbol='@^GSPC' I ALWAYS get 51 results! it's impossible, take a look at: http://it.finance.yahoo.com/q/cp?s=^GSPC There are 500 results! I also tried some paging parameters. select * from yahoo.finance.quoteslist(50,30) where symbol='@^GSPC' (to get from 50 to 80) select * from yahoo.finance.quoteslist(100) where symbol='@^GSPC' (to get the first 100 results) select * from yahoo.finance.quoteslist where symbol='@^GSPC' limit 30 offset 50 but ALWAYS the last stock is: <quote symbol="BBY"> <Symbol>BBY</Symbol> <LastTradePriceOnly>41.03</LastTradePriceOnly> <LastTradeDate>5/7/2010</LastTradeDate> <LastTradeTime>4:00pm</LastTradeTime> <Change>-0.48</Change> <Open>41.35</Open> <DaysHigh>42.35</DaysHigh> <DaysLow>39.60</DaysLow> <Volume>14129531</Volume> </quote> Why do I have this kind of problem? Thank you so much for your support! (P.S. I've tested it on Yahoo YQL console)

    Read the article

  • Can't get this SPARQL query to work

    - by Jason
    Okay, I'm just learning to use SPARQL to query data from dbpedia.org and I'm using dbpedia's http://dbpedia.org/snorql/ to run my queries in. I am trying to get a list of MusicalArtists based on searching for the same string over three fields like so: SELECT ?subject ?artistRdfsLabel ?artistFoafName ?artistDbpedia2Name WHERE { ?subject rdf:type <http://dbpedia.org/ontology/MusicalArtist> . OPTIONAL { ?subject rdfs:label ?artistRdfsLabel . } OPTIONAL { ?subject foaf:name ?artistFoafName . } OPTIONAL { ?subject dbpedia2:name ?artistDbpedia2Name . } FILTER ( str(?artistRdfsLabel) = "Stevie Nicks" || str(?artistFoafName) = "Stevie Nicks" || str(?artistDbpedia2Name) = "Stevie Nicks" ) } LIMIT 10 This works because "Stevie Nicks" has all three fields (rdfs:label, foaf:name, dbpedia2:name). But when I try to query by another MusicalArtist that doesn't have all three ("Depeche Mode" for example) I get no results. I have tried various things like BIND(COALESCE(?field,...,...) AS ?artistName) to filter by ?artistName and I also tried UNION but nothing seems to work. Can someone point out the error of my SPARQL ways? :) Thanks! Jason

    Read the article

  • problem in fetching data from several tables in one query

    - by Mac Taylor
    hey guys in an attempt to union my querries into one query to database , now im in need of geting username of first poster and last poster of a topic in my forums here is my code to do as i told :: $result = $db->sql_query("SELECT t.*,p.*,u.* SUM(t.topic_approved='1') AS Amount_Of_Topics, SUM(p.post_approved ='1') AS Amount_Of_Posts FROM bb3topics t, bb3posts p, bb3users u GROUP BY t.topic_last_post_id ORDER BY t.topic_last_post_id DESC LIMIT 10 " ); while( $row = $db->sql_fetchrow($result) ) { $Amount_Of_Topics = $row['Amount_Of_Topics']; $Amount_Of_Posts = $row['Amount_Of_Posts']; $Amount_Of_Topic_Replies = $Amount_Of_Topic_Replies + $row['topic_replies']; $Amount_Of_Topic_Views = $Amount_Of_Topic_Views + $row['topic_views']; $topic_id = $row['topic_id']; $forum_id = $row['forum_id']; $topic_last_post_id = $row['topic_last_post_id']; $topic_title = $row['topic_title']; $topic_poster = $row['topic_poster']; $topic_views = $row['topic_views']; $topic_replies = $row['topic_replies']; $topic_moved_id = $row['topic_moved_id']; $topic_time = $row['topic_time']; $result2 = $db->sql_query( "SELECT topic_id, poster_id, post_time FROM bb3posts where post_id = '$topic_last_post_id'" ); list( $topic_id, $poster_id, $post_time ) = $db->sql_fetchrow( $result2 ); $result3 = $db->sql_query( "SELECT username, user_id FROM bb3users where user_id='$poster_id'" ); list( $uname, $uid ) = $db->sql_fetchrow( $result3 ); $LastPoster = "$uname"; $result4 = $db->sql_query( "SELECT username, user_id FROM bb3users where user_id='$topic_poster'" ); list( $uname, $uid ) = $db->sql_fetchrow( $result4 ); $OrigPoster = "$uname"; now i need to query all this together not in separated ones i tried using left join but didn't worked what mysql conjunction should i use ?!

    Read the article

  • Query with many CASE statements - optimization

    - by Nemanja Vujacic
    Hi guys, I have one very dirty query that per sure can be optimized because there are so many CASE statements in it! SELECT (CASE pa.KplusTable_Id WHEN 1 THEN sp.sp_id WHEN 2 THEN fw.fw_id WHEN 3 THEN s.sw_Id WHEN 4 THEN id.ia_id END) as Deal_Id, max(CASE pa.KplusTable_Id WHEN 1 THEN sp.Trans_Id WHEN 2 THEN fw.Trans_Id WHEN 3 THEN s.Trans_Id WHEN 4 THEN id.Trans_Id END) as TransId_CurrentMax INTO #MaxRazlicitOdNull FROM #PotencijalniAktuelni pa LEFT JOIN kplus_sp sp (nolock) on sp.sp_id=pa.Deal_Id AND pa.KplusTable_Id=1 LEFT JOIN kplus_fw fw (nolock) on fw.fw_id=pa.Deal_Id AND pa.KplusTable_Id=2 LEFT JOIN dev_sw s (nolock) on s.sw_Id=pa.Deal_Id AND pa.KplusTable_Id=3 LEFT JOIN kplus_ia id (nolock) on id.ia_id=pa.Deal_Id AND pa.KplusTable_Id=4 WHERE isnull(CASE pa.KplusTable_Id WHEN 1 THEN sp.BROJ_TIKETA WHEN 2 THEN fw.BROJ_TIKETA WHEN 3 THEN s.tiket WHEN 4 THEN id.BROJ_TIKETA END, '')<>'' GROUP BY CASE pa.KplusTable_Id WHEN 1 THEN sp.sp_id WHEN 2 THEN fw.fw_id WHEN 3 THEN s.sw_Id WHEN 4 THEN id.ia_id END Because I have same condition couple times, do you have idea how to optimize query, make it simpler and better. All suggestions are welcome! TnX in advance! Nemanja

    Read the article

  • YAHOO QUERY LANGUAGE BUG!

    - by Damiano
    Hello everybody! Today, I've started with Yahoo Query Language. I would use it to retrive stocks details, so I'm talking about Yahoo Finance. I think there is a bug on this language. This is my query: select * from yahoo.finance.quoteslist where symbol='@^GSPC' I ALWAYS get 51 results! it's impossible, take a look at: http://it.finance.yahoo.com/q/cp?s=^GSPC There are 500 results! I also tried some paging parameters. select * from yahoo.finance.quoteslist(50,30) where symbol='@^GSPC' (to get from 50 to 80) select * from yahoo.finance.quoteslist(100) where symbol='@^GSPC' (to get the first 100 results) select * from yahoo.finance.quoteslist where symbol='@^GSPC' limit 30 offset 50 but ALWAYS the last stock is: <quote symbol="BBY"> <Symbol>BBY</Symbol> <LastTradePriceOnly>41.03</LastTradePriceOnly> <LastTradeDate>5/7/2010</LastTradeDate> <LastTradeTime>4:00pm</LastTradeTime> <Change>-0.48</Change> <Open>41.35</Open> <DaysHigh>42.35</DaysHigh> <DaysLow>39.60</DaysLow> <Volume>14129531</Volume> </quote> Why do I have this kind of problem? Thank you so much for your support! (P.S. I've tested it on Yahoo YQL console)

    Read the article

  • mysql whats wrong with this query?

    - by Hailwood
    I'm trying to write a query that selects from four tables campaignSentParent csp campaignSentEmail cse campaignSentFax csf campaignSentSms css Each of the cse, csf, and css tables are linked to the csp table by csp.id = (cse/csf/css).parentId The csp table has a column called campaignId, What I want to do is end up with rows that look like: | id | dateSent | emailsSent | faxsSent | smssSent | | 1 | 2011-02-04 | 139 | 129 | 140 | But instead I end up with a row that looks like: | 1 | 2011-02-03 | 2510340 | 2510340 | 2510340 | Here is the query I am trying SELECT csp.id id, csp.dateSent dateSent, COUNT(cse.parentId) emailsSent, COUNT(csf.parentId) faxsSent, COUNT(css.parentId) smsSent FROM campaignSentParent csp, campaignSentEmail cse, campaignSentFax csf, campaignSentSms css WHERE csp.campaignId = 1 AND csf.parentId = csp.id AND cse.parentId = csp.id AND css.parentId = csp.id; Adding GROUP BY did not help, so I am posting the create statements. csp CREATE TABLE `campaignsentparent` ( `id` int(11) NOT NULL AUTO_INCREMENT, `campaignId` int(11) NOT NULL, `dateSent` datetime NOT NULL, `account` int(11) NOT NULL, `status` varchar(15) NOT NULL DEFAULT 'Creating', PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=latin1 cse/csf (same structure, different names) CREATE TABLE `campaignsentemail` ( `id` int(11) NOT NULL AUTO_INCREMENT, `parentId` int(11) NOT NULL, `contactId` int(11) NOT NULL, `content` text, `subject` text, `status` varchar(15) DEFAULT 'Pending', PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=140 DEFAULT CHARSET=latin1 css CREATE TABLE `campaignsentsms` ( `id` int(11) NOT NULL AUTO_INCREMENT, `parentId` int(11) NOT NULL, `contactId` int(11) NOT NULL, `content` text, `status` varchar(15) DEFAULT 'Pending', PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=141 DEFAULT CHARSET=latin1

    Read the article

  • Java MySQL Query Problem MySQLSyntaxErrorException When Creating a Table

    - by Aqib Mushtaq
    I fairly new to MySQL with Java, but I have executed a few successful INSERT queries however cannot seem to get the CREATE TABLE query to execute without getting the 'MySQLSyntaxErrorException' exception. My code is as follows: import java.sql.*; Statement stmt; Class.forName("com.mysql.jdbc.Driver"); String url = "jdbc:mysql://localhost:3306/mysql"; Connection con = DriverManager.getConnection(url, "root", "password"); stmt = con.createStatement(); String tblSQL = "CREATE TABLE IF NOT EXISTS \'dev\'.\'testTable\' (\n" + " \'id\' int(11) NOT NULL AUTO_INCREMENT,\n" + " \'date\' smallint(6) NOT NULL\n" + ") ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;"; stmt.executeUpdate(tblSQL); stmt.close(); con.close(); And the error is as follows: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''dev'.'testTable' ( 'id' int(11) NOT NULL AUTO_INCREMENT, 'date' smallint(6) N' at line 1 I would appreciate it if anyone could spot the mistake in this query, as I've tried executing this within phpMyAdmin and it works as it should. Thanks in advance.

    Read the article

  • Optimizing an embedded SELECT query in mySQL

    - by Crazy Serb
    Ok, here's a query that I am running right now on a table that has 45,000 records and is 65MB in size... and is just about to get bigger and bigger (so I gotta think of the future performance as well here): SELECT count(payment_id) as signup_count, sum(amount) as signup_amount FROM payments p WHERE tm_completed BETWEEN '2009-05-01' AND '2009-05-30' AND completed > 0 AND tm_completed IS NOT NULL AND member_id NOT IN (SELECT p2.member_id FROM payments p2 WHERE p2.completed=1 AND p2.tm_completed < '2009-05-01' AND p2.tm_completed IS NOT NULL GROUP BY p2.member_id) And as you might or might not imagine - it chokes the mysql server to a standstill... What it does is - it simply pulls the number of new users who signed up, have at least one "completed" payment, tm_completed is not empty (as it is only populated for completed payments), and (the embedded Select) that member has never had a "completed" payment before - meaning he's a new member (just because the system does rebills and whatnot, and this is the only way to sort of differentiate between an existing member who just got rebilled and a new member who got billed for the first time). Now, is there any possible way to optimize this query to use less resources or something, and to stop taking my mysql resources down on their knees...? Am I missing any info to clarify this any further? Let me know... EDIT: Here are the indexes already on that table: PRIMARY PRIMARY 46757 payment_id member_id INDEX 23378 member_id payer_id INDEX 11689 payer_id coupon_id INDEX 1 coupon_id tm_added INDEX 46757 tm_added, product_id tm_completed INDEX 46757 tm_completed, product_id

    Read the article

  • SQL query to get latest record for all distinct items in a table

    - by David Buckley
    I have a table of all sales defined like: mysql> describe saledata; +-------------------+---------------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------------------+---------------------+------+-----+---------+-------+ | SaleDate | datetime | NO | | NULL | | | StoreID | bigint(20) unsigned | NO | | NULL | | | Quantity | int(10) unsigned | NO | | NULL | | | Price | decimal(19,4) | NO | | NULL | | | ItemID | bigint(20) unsigned | NO | | NULL | | +-------------------+---------------------+------+-----+---------+-------+ I need to get the last sale price for all items (as the price may change). I know I can run a query like: SELECT price FROM saledata WHERE itemID = 1234 AND storeID = 111 ORDER BY saledate DESC LIMIT 1 However, I want to be able to get the last sale price for all items (the ItemIDs are stored in a separate item table) and insert them into a separate table. How can I get this data? I've tried queries like this: SELECT storeID, itemID, price FROM saledata WHERE itemID IN (SELECT itemID from itemmap) ORDER BY saledate DESC LIMIT 1 and then wrap that into an insert, but it's not getting the proper data. Is there one query I can run to get the last price for each item and insert that into a table defined like: mysql> describe lastsale; +-------------------+---------------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------------------+---------------------+------+-----+---------+-------+ | StoreID | bigint(20) unsigned | NO | | NULL | | | Price | decimal(19,4) | NO | | NULL | | | ItemID | bigint(20) unsigned | NO | | NULL | | +-------------------+---------------------+------+-----+---------+-------+

    Read the article

  • MySQL LIMIT 1 but query 15 rows?

    - by Ian
    Basically what I'm trying to do is compare the ID's of rows against 15 results in MySQL, eliminating all but 1 (using NOT IN) and then pull that result. Now normally this would be fine by itself, however the order of the 15 rows I'm doing the SQL query for are constantly changing based on a ranking, so there is a possibility that between the time the ranking updates, and the ajax request (which I submit the ID's for NOT IN) more than just one ID has changed, which would of course bring back more than one row which I do not want. So in short, is there a way in which I can query 15 rows, but only return one? Without having to run two separate queries. Any help is appreciated, thank you. EXAMPLE: Say I have 7 items in my database, and I'm displaying 5 on the page to the user. These are what are being displayed to the user: Apple Orange Kiwi Banana Grape But in the database I also have Peach Blackberry Now what I want to do is if the user deletes an item from their list, it will add another item (based on a ranking they have) Now the issue is, in order to know what they have on their list at the moment I send the remaining items to the database (say they deleted Kiwi, I would send Apple, Orange, Banana, and Grape) So now I select the highest ranked 5 items from are remaining six items, make sure they are not the ones already displayed on the page, and then add the new one to list (either Peach or Blackberry) All good and well, except that if both peach and blackberry now outrank grape, then I will be returning two results instead of just one. Because it would've searched... Apple Orange Banana Peach Blackberry and excluded... Apple Orange Banana Grape Which leaves us with both Peach and Blackberry, instead of just Peach or Blackberry

    Read the article

  • build SQL query string using user input

    - by user175084
    i have to make a string by using the values which the user selects on the webpage suppose i need to display files for multiple machines with differnt search criteria.. i currently use this code: DataTable dt = new DataTable(); SqlConnection connection = new SqlConnection(); connection.ConnectionString = ConfigurationManager.ConnectionStrings["DBConnectionString"].ConnectionString; connection.Open(); SqlCommand sqlCmd = new SqlCommand("SELECT FileID FROM Files WHERE MachineID=@machineID and date= @date", connection); SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd); sqlCmd.Parameters.AddWithValue("@machineID", machineID); sqlCmd.Parameters.AddWithValue("@date", date); sqlDa.Fill(dt); now this is fixed query where the user just has one machine and just selects one date... i want to make a query in which the user has multiple search options like type or size if he wants depending on what he selects also if he can select multiple machines.. SELECT FileID FROM Files WHERE (MachineID=@machineID1 or MachineID = @machineID2...) and (date= @date and size=@size and type=@type... ) all of this happens in runtime... other wise i have to create a for loop to put multiple machines one by one... and have multiple queries depending on the case the user selected... this is quiet interesting and i could use some help... thanks

    Read the article

  • Fix N+1 query in "declarative_authorization" gem using gem "bullet"

    - by makaroni4
    Currently I am working on one big web application and to make it work faster I decided to refactor all N+1 queries (to decrease number of requests to database, http://rails-bestpractices.com/posts/29-fix-n-1-queries). So I installed gem "bullet" which doesn`t work with Rails 3.1.1 now (you can use fork from https://github.com/flyerhzm/bullet). When using declarative_authorization gem on each page I get same alerts: N+1 Query detected Role => [:permissions] Add to your finder: :include => [:permissions] N+1 Query detected Permission => [:permission_rules] Add to your finder: :include => [:permission_rules] CACHE (0.0ms) SELECT "roles".* FROM "roles" CACHE (0.0ms) SELECT "permissions".* FROM "permissions" WHERE "permissions"."role_id" = 1 CACHE (0.0ms) SELECT "permissions".* FROM "permissions" WHERE "permissions"."role_id" = 2 CACHE (0.0ms) SELECT "permissions".* FROM "permissions" WHERE "permissions"."role_id" = 3 CACHE (0.0ms) SELECT "permissions".* FROM "permissions" WHERE "permissions"."role_id" = 4 CACHE (0.0ms) SELECT "permissions".* FROM "permissions" WHERE "permissions"."role_id" = 6 CACHE (0.0ms) SELECT "permissions".* FROM "permissions" WHERE "permissions"."role_id" = 7 CACHE (0.0ms) SELECT "permissions".* FROM "permissions" WHERE "permissions"."role_id" = 8 CACHE (0.0ms) SELECT "permission_rules".* FROM "permission_rules" INNER JOIN "permission_rules_permissions" ON "permission_rules"."id" = "permission_rules_permissions"."permission_rule_id" WHERE "permission_rules_permissions"."permission_id" = 30 CACHE (0.0ms) SELECT "permission_rules".* FROM "permission_rules" INNER JOIN "permission_rules_permissions" ON "permission_rules"."id" = "permission_rules_permissions"."permission_rule_id" WHERE "permission_rules_permissions"."permission_id" = 31 ... Could you please help me with that and to make this queries faster?

    Read the article

  • help with delete where not in query

    - by kralco626
    I have a lookup table (##lookup). I know it's bad design because I'm duplicating data, but it speeds up my queries tremendously. I have a query that populates this table insert into ##lookup select distinct col1,col2,... from table1...join...etc... I would like to simulate this behavior: delete from ##lookup insert into ##lookup select distinct col1,col2,... from table1...join...etc... This would clearly update the table correctly. But this is a lot of inserting and deleting. It messes with my indexes and locks up the table for selecting from. This table could also be updated by something like: delete from ##lookup where not in (select distinct col1,col2,... from table1...join...etc...) insert into ##lookup (select distinct col1,col2,... from table1...join...etc...) except if it is already in the table The second way may take longer, but I can say "with no lock" and I will be able to select from the table. Any ideas on how to write the query the second way?

    Read the article

< Previous Page | 13 14 15 16 17 18 19 20 21 22 23 24  | Next Page >